Message Boards Message Boards

0
|
1303 Views
|
3 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Avoid trouble while using two if Statements?

Posted 6 years ago

Hi ! How are you guys!

So I am using the following code to randomly to choose x or y first, then another if statement to choose to add or minus. However, some error pop out and I don't know how to solve. It would be so appreciated if you guys can help with this silly problem!

Thanks so much!!! Code:

x = 0;
y = 0;
lstx = {};
lsty = {};
For[i = 0, i < 1000, i++,
 a = RandomReal[];
 b = RandomReal[];
 c = RandomReal[];
 If[ c < 0.5,
  (If[a > 0.5, x = x + 1, x = x - 1];
   AppendTo[lstx, x]),
  (If[b > 0.5, y = y + 1, y = y - 1];
   AppendTo[lsty, y])
  ]]

error:$RecursionLimit
Attachments:
POSTED BY: Jack benjamin
3 Replies

I cannot replicate the message nor can I see anything amiss with the code (other than AppendTo is not the most efficient way to go about this).

Here is one way to make the code more efficient.

x = 0; y = 0;
{lstx, lsty} = Reap[For[i = 0, i < 100, i++,
    {a, b, c} = RandomReal[1, {3}];
    If[c < 0.5,
     If[a > 0.5, x = x + 1, x = x - 1]; Sow[x, "lstx"],
     If[b > 0.5, y = y + 1, y = y - 1]; Sow[y, "lsty"]
     ]], {"lstx", "lsty"}][[2, All, 1]]

(* Out[44]= {{-1, 0, 1, 0, 1, 0, 1, 2, 3, 2, 3, 4, 3, 2, 3, 4, 3, 2, 1, 
  2, 1, 2, 1, 2, 1, 0, -1, 0, -1, 0, 1, 2, 3, 2, 3, 4, 5, 6, 5, 4, 3, 
  2, 1, 0, -1, 0, 1}, {-1, -2, -1, -2, -1, -2, -1, 0, 1, 2, 1, 2, 3, 
  2, 1, 2, 3, 2, 3, 4, 3, 4, 3, 2, 1, 2, 1, 0, 1, 2, 1, 2, 3, 4, 3, 4,
   5, 6, 7, 6, 7, 6, 5, 4, 3, 2, 1, 2, 1, 0, -1, 0, -1}} *)

One could make further improvements but they would be more for elegance (whatever that means) than speed.

POSTED BY: Daniel Lichtblau
Posted 6 years ago

First, Thanks for your help Daniel! However, it just won't work and could you be more specific how to improve this?

Sincerely

Jack

POSTED BY: Jack benjamin
Posted 6 years ago
My code( Sorry for the previous inconvenience): 
x = 0;
y = 0;
lstx = {};
lsty = {};
For[i = 0, i < 1000, i++,
 a = RandomReal[];
 b = RandomReal[];
 c = RandomReal[];
 If[ c < 0.5,
  (If[a > 0.5, x = x + 1, x = x - 1];
   AppendTo[lstx, x]),
  (If[b > 0.5, y = y + 1, y = y - 1];
   AppendTo[lsty, y])
  ]]
POSTED BY: Jack benjamin
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract