对于以下伪代码,我在本文末尾编写了代码。但是对于使用x(i)
和x(i-1)
,代码会出错
NameError: name 'xt' is not defined
我们这里的函数是def F (x)
。随机数u
即uniform(0,1)
。 i=1...N
。我们将x[0]
定义为初始点。
xt[i]=x[i-1]+u
如果F(x[i])>1
则x[i]=xt[i]
,否则x[i]=x[i-1]
步骤将继续从1
到N
。
我从1到3写了4个样本行,以便进一步说明。
i=1 if F(x[1])>1 then x[1]=xt[1], otherwise x[1]=x[0]
which xt[1]=x[0]+u and here x[0] is our initial point
i=2 if F(x[2])>1 then x[2]=xt[2], otherwise x[2]=x[1]
which xt[2]=x[1]+u and x[1] is the point of step 1
i=3 if F(x[3])>1 then x[3]=xt[3], otherwise x[3]=x[2]
which xt[3]=x[2]+u and x[2] is the point of step 2
i=4 if F(x[3])>1 then x[4]=xt[4], otherwise x[4]=x[3]
which xt[4]=x[3]+u and x[3] is the point of step 2
.... i=N
代码是:
import numpy as np
import math
from math import *
x=[0.8]
N=10
R = np.random.uniform(0, 5)
def a(z):
return sqrt(z)
for i in range(1,N):
xt[i]=x[i-1]+u
if a(xt[i])>1:
x[i]=xt[i]
else:
x[i]=x[i-1]
print(x[i])
感谢您的帮助。
答案 0 :(得分:1)
使用词典:
import numpy as np
import math
from math import *
x = { 0: 0.8 }
xt = {}
N=10
u = np.random.uniform(0, 5)
def a(z):
return sqrt(z)
for i in range(1,N):
xt[i]=x[i-1]+u
if a(xt[i])>1:
x[i]=xt[i]
else:
x[i]=x[i-1]
print(x[i])