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: [mg40128] Re: simple question if/while loop
  • From: Bill Rowe <listuser at earthlink.net>
  • Date: Fri, 21 Mar 2003 02:39:01 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

On 3/20/03 at 3:35 AM, kpsj2002 at yahoo.com (s kp) wrote:

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?

You have used If and While correctly. The reason you are getting a a number times a Null is you are missing a semicolon after the While loop. Without the semicolon Mathematica sees the expression as While[] tb and preforms the indicated multiplication. Adding the semicolon will make this work as expected.

Now having said that, this codes is very inefficient.

If[#>.5,#,0]&/@Table[Random[],{4}]

will create the same output as your code above.

Even if you want to use the While loop rather than mapping If to list of numbers as I've done here your code could be made more efficient

For example

Fun[] :=
  Module[{tb = Table[Random[], {4}], n = 1}, 
    While[n < 5,
      If[tb[[n]] < .5, tb[[n]] = 0];
      n++];
    tb]
    
 Will produce the same output. 


  • Prev by Date: Re: simple question if/while loop
  • Next by Date: Re: combinatorics problem
  • Previous by thread: Re: simple question if/while loop
  • Next by thread: Re: simple question if/while loop