MathGroup Archive 2003

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: simple question if/while loop

  • To: mathgroup at smc.vnet.net
  • Subject: [mg40126] Re: simple question if/while loop
  • From: "Bill Bertram" <wkb at ansto.gov.au>
  • Date: Fri, 21 Mar 2003 02:38:44 -0500 (EST)
  • Organization: Australian Nuclear Science and Technology Organisation
  • References: <b5bk79$5t4$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

"s kp" <kpsj2002 at yahoo.com> wrote in message
news:b5bk79$5t4$1 at smc.vnet.net...
> I am trying to do the following for a test purpose so I am a learning
mathematica
>
> TestFun[] := Module[{a, tb, n},
>     tb = Table[0.0, {4}];
>     n := 1;
>     a := Random[];
>     While[n < 5,
>         If[ a > .5,
>           (tb[[n]] = a;
>             n++;), Continue[]
>           ]
>         ]
>       tb
>     ]
>
> The output that I get is
>
> {0.871577 Null, 0.512558 Null, 0.00441806 Null, 0.520545 Null}
>
> Why am I doing wrong here and what is the correct way to do the above
thing using If and While loop?

Getting rid of the "Null" in the output is easy. You need to insert a
semicolon after the last "]" of the While statement.
However, you have to remember that each time you mention "a" in your code
you generate a new random number. So if, as appears from your coding, you
are trying to select only random numbers greater than 0.5 then your method
won't work. Instead you need to write the "If" statement as,

     If[ (tb[n] = a) > 0.5, n++, Continue[]]

Cheers,
  Bill




  • Prev by Date: Re: Finding solutions to differential eqns
  • Next by Date: Re: simple question if/while loop
  • Previous by thread: Re: simple question if/while loop
  • Next by thread: Re: simple question if/while loop