2017-01-04 100 views
-1

我想知道是否有人知道如何將此隨機變量的VBA代碼轉換爲Python。 (「已保存的」變量是VBA布爾)Marsaglia bray,將VBA代碼轉換爲Python

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

正確的壓痕,什麼是不工作 – depperm

+0

VBA:'如果保存=假Then',蟒蛇'如果保存==真:'。你是真的嗎? –

+0

indentation NOT correct - 如果在相同縮進級別,請參閱def –

回答

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 
+0

謝謝你,代碼工作完美! –