Marsaglia bray,将VBA代码转换为Python

2024-10-01 04:59:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有人知道如何将用于随机变量生成的VBA代码转换成Python。 (“Saved”变量是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

我自己也试过这个代码,但没有成功:

^{pr2}$

Tags: 代码falseifasfunctionvbaenddouble
1条回答
网友
1楼 · 发布于 2024-10-01 04:59:34

不需要在许多其他语言中需要真正可怕的结构!在

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

相关问题 更多 >