[Date Index]
[Thread Index]
[Author Index]
Re: Relational Operators and Random Integers
*To*: mathgroup at smc.vnet.net
*Subject*: [mg90330] Re: Relational Operators and Random Integers
*From*: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
*Date*: Sun, 6 Jul 2008 07:18:30 -0400 (EDT)
*Organization*: The Open University, Milton Keynes, UK
*References*: <g4ncm0$gd3$1@smc.vnet.net>
Peter Evans wrote:
> 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?
The issue is about SetDelayed vs Set ( := or = ), that is between
delayed assignment vs immediate assignment.
SetDelayed ( := ) tells Mathematica to evaluate the RHS of the
expression only when the LHS is called and *every time* the LHS is
called. So in your case, x is evaluated a for the first time on the
"second" line and it is evaluated again when Mathematica evaluates the
Which statement.
On the other hand, Set ( = ) evaluates immediately the RHS and assigns
the result to x. After that, RandomChoice is not evaluated again and the
value of x stays constant. In the example below, notice that there are
three output lines (with SetDelayed there are only two since the first
expression is not evaluated immediately).
In[1]:= x = RandomChoice[{1, 2, 3}]
x
Which[x == 1, 1, x == 2, 2, x == 3, 3]
Out[1]= 2
Out[2]= 2
Out[3]= 2
See "Immediate and Delayed Definitions"
http://reference.wolfram.com/mathematica/tutorial/ImmediateAndDelayedDefinitions.html
Regards,
-- Jean-Marc
Prev by Date:
**Re: Relational Operators and Random Integers**
Next by Date:
**Re: Relational Operators and Random Integers**
Previous by thread:
**Re: Relational Operators and Random Integers**
Next by thread:
**Re: Relational Operators and Random Integers**
| |