samedi 14 avril 2018

Saving the value of previous step to use in next step in Python

For the following pseudo code I wrote the code at the end of this text. But for using x(i) and x(i-1) the code gets error NameError: name 'xt' is not defined

We have a function here is def F (x). And random number u which is uniform(0,1). i=1...N. we define a x[0] as initial point.

xt[i]=x[i-1]+u

If F(x[i])>1 then x[i]=xt[i], otherwise x[i]=x[i-1]

the steps will continue to from 1 to N.

I write 4 sample lines from 1 to 3 for more clarification.

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

the code is:

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])

I appreciate your help.

Aucun commentaire:

Enregistrer un commentaire