我想知道是否有人知道如何将这个随机变量生成的VBA代码转换为Python。 (“已保存”变量是VBA中的布尔值)
function MarsagliaBrayNormSRnd() As Double
Dim U1 As Double, U2 As Double
Dim x As Double, Y As Double
If Saved = False Then
x = 2
While x > 1
U1 = (2 * Rnd() - 1)
U2 = (2 * Rnd() - 1)
x = (U1 * U1) + (U2 * U2)
Wend
Y = Sqr(-2 * Log(x) / x)
MarsagliaBrayNormSRnd = U1 * Y
SavedNormSRnd = U2 * Y
Saved = True
Else
MarsagliaBrayNormSRnd = SavedNormSRnd
Saved = False
End If
End Function
我自己尝试了这段代码,但没有让它工作:
import math
import pandas as pd
import numpy as np
def MarsagliaBrayNormSRnd(u1,u1,x,y):
if Saved==False:
x = 2
while x > 1:
np.random.seed(1)
u1 = 2 * np.random.random((3,1)) - 1
u2 = 2 * np.random.random((3,1)) - 1
x = (u1 * u1) + (u2 * u2)
y = math.sqrt(-2 * math.log(x) / x)
MarsagliaBrayNormSRnd = u1 * y
SavedNormSRnd = u2 * y
Saved = True
else:
MarsagliaBrayNormSRnd = SavedNormSRnd
Saved = False
答案 0 :(得分:1)
不需要许多其他语言所需的真正可怕的结构!
from random import random
from numpy import sqrt, log
def MarsagliaBrayNormSRnd():
while True:
x = 2
while x > 1:
u1 = 2 * random() - 1
u2 = 2 * random() - 1
x = (u1 * u1) + (u2 * u2)
y = sqrt( -2 * log(x) / x )
yield u1 * y
yield u2 * y
for i, N in enumerate(MarsagliaBrayNormSRnd()):
print (N)
if i>10:
break