# Avoid trouble while using two if Statements?

Posted 7 months ago
373 Views
|
3 Replies
|
1 Total Likes
|
 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:
3 Replies
Sort By:
Posted 7 months 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]) ]] 
 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.