0

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.

Dan
  • 47
  • 5
  • Thank you very much for your reply. I missed ']' at the end. Please see the edited code. I called it using f[{1, 2, 3}]. However, it still didn't return anything. – Dan Nov 07 '21 at 01:32
  • Try 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:34
  • It works now! Thank you very much for your help! – Dan Nov 07 '21 at 01:37
  • You're welcome. :) – Michael E2 Nov 07 '21 at 01:39
  • It is better to avoid For. You can always replace it by Do, like this f[x0_] := Module[{r = RandomReal[], s = 0}, Do[s += x0[[i]]; If[r <= s, Return[i, Module]], {i, 3} ] ]; then call as f[{.1, .3, .4}] – Nasser Nov 07 '21 at 02:46
  • @ Nasser, thank you so much for your help. I replaced the for loop with Do. The efficiency is super improved. – Dan Nov 08 '21 at 03:56

0 Answers0