I tried to use Mathematica to implement random generator. The pseudo code I use is as following:
r = RandomReal[]
s = 0
loop j = 0 ... 2^n - 1
s += p_j
if r <= s then
output[j] and exit
End if
End Loop
I tried following code, which didn't return anything.
f[x0_] :=
Module[{r = RandomReal[], s = 0},
For[i = 0, i < 3, i++; s += x0[[i]];
If[r <= s, Return[i], Continue[] ];];
]
f[{1, 2, 3}]
May I ask what's wrong with my code? Any suggestions would be appreciated very much.
Return[i, Module]. See also https://mathematica.stackexchange.com/questions/134609/why-should-i-avoid-the-for-loop-in-mathematica and https://mathematica.stackexchange.com/questions/6815/what-can-i-use-as-the-second-argument-to-return-in-my-own-functions and here in the docs, http://reference.wolfram.com/mathematica/ref/message/Break/nofunc.html – Michael E2 Nov 07 '21 at 01:34For. You can always replace it byDo, like thisf[x0_] := Module[{r = RandomReal[], s = 0}, Do[s += x0[[i]]; If[r <= s, Return[i, Module]], {i, 3} ] ];then call asf[{.1, .3, .4}]– Nasser Nov 07 '21 at 02:46