MathGroup Archive 2008

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

Search the Archive

Re: Relational Operators and Random Integers


First, the x you have before the Which statement is irrelevant. It returns a 
random choice but has nothing to do with the 'x's that are in the Which 

Note that Which has the attribute HoldAll.

{HoldAll, Protected}

Then read carefully the Help for Which. It evaluates each of the tests in 
turn (and each time uses a new random choice for x) and then returns the 
first case that is True. It also means that it may not get a hit because 
each new generation of x may miss its particular case. Evaluate the 
following repeatedly.

Which[x == 1, 1, x == 2, 2, x == 3, 3, True, "No hit"]

Or better yet, evaluate the following where you can see what is going on at 
each step.

 Print[xfix = x]; xfix == 1, 1,
 Print[xfix = x]; xfix == 2, 2,
 Print[xfix = x]; xfix == 3, 3,
 True, "No hit"]

You could use the Switch statement as follows:

Switch[xfix = x, 1, 1, 2, 2, 3, 3]

or you could use a Module to fix the value to a single random choice:

Module[{xfix = x},
 Which[xfix == 1, 1, xfix == 2, 2, xfix == 3, 3, True, "No hit"]]

Or you could use a trick with the With statement. With calculates the 
internal value of x by evaluating the external value and then replaces that 
single value everywhere within the With statement and only then evaluates 
the statements.

With[{x = x},
 Which[x == 1, 1, x == 2, 2, x == 3, 3, True, "No hit"]]

David Park
djmpark at

"Peter Evans" <peter.w.evans at> wrote in message 
news:g4ncm0$gd3$1 at
> Hi all,
> I'm a new user of Mathematica 6 and am struggling with some basics. I wish 
> to write a set of rules which are dependent upon a random variable. I've 
> been using RandomChoice to choose my variable and then large If and Which 
> statements to produce my desired dynamics.
> The problem is that the number that these statements end up spitting out 
> aren't recognised as what they are in further If and Which statements. 
> Here's a simple example that demonstrates my problem:
> In[1]:= x := RandomChoice[{1, 2, 3}]
> x
> Which[x == 1, 1, x == 2, 2, x == 3, 3]
> Out[2]= 1
> Out[3]= 2
> Mathematica clearly thinks x to be 1 but the If statement indicates its 2. 
> What am I doing wrong here?
> Much thanks,
> Pete

  • Prev by Date: Re: Relational Operators and Random Integers
  • Next by Date: Re: Re: Re: Re: Problem with
  • Previous by thread: Re: Relational Operators and Random Integers
  • Next by thread: Re: Relational Operators and Random Integers