Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2003
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

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: [mg40115] Re: simple question if/while loop
  • From: atelesforos at hotmail.com (Orestis Vantzos)
  • Date: Fri, 21 Mar 2003 02:36:44 -0500 (EST)
  • References: <b5bk79$5t4$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

a:=Random[] is a 'delayed' assignment which means that a will give a
new random number every time it is called.
Hence a>.5 will test one number but tb[[n]]=a will store another!
Use a=Random[] instead and move it inside the While.

By the way your code is a very bad example of Mathematica programming;
Mathematica is better programmed using list operations, like Join, Inner, etc.

It's better to begin with an empty list tb={} and just add the new
elements using Join.
I would recommend something like the following:


TestListFun[]:=Module[{a,tb,n},
   tb = {};
   n = 1;
   While[ n<5,
      a = Random[];
      If[ a>.5, Join[tb,{a}];n++];
   (* no need for Continue[] *)
   ];
   tb
]

Realizing that n is just the length of the list we can just use the
following:

TestListFun2[]:=Module[{tb,a},
   tb = {};
   While[ Length[tb]<4,
      a = Random[];
      If[a>.5, Join[tb,{a}]]; 
   ]
   tb
]

Finally the functional approach:

NestWhile[
  Module[{a}, If[(a = Random[]) > .5, Join[#, {a}], #]] &, 
  {}, 
  Length[#] < 4 &
]

will return what you want.
Orestis

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?
> 
> thanks


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