Search code examples
pythonarraysrandomkeyerror

KeyError 3 in python when more dictionaries are added


I wrote the following code. The code is running well. But when I add yt[i]=y[i-1]+delta(R1,R2) it gets an error:

yt[i]=y[i-1]+delta(R1,R2) KeyError: 1

the function a is just an example and is not the real one.

import numpy as np
import math
from math import *

x  = { 0: 0.3 }
xt = {}
N=10
y  = { 0: 0.2 }
yt = {}

def a(z,s):
    return sqrt(z)+s

def delta(r1,r2):
        sig=0.055
        d=sig*(np.sqrt(-2*np.log(r1))*np.cos(np.radians(r2)))
        return d

for i in range(1,N):
    R1=np.random.uniform(0,1)
    R2=np.random.uniform(0,1)
    R3=np.random.uniform(0,1)

    xt[i]=x[i-1]+delta(R1,R2)
    yt[i]=y[i-1]+delta(R1,R2)

    if a(xt[i],yt[i])>R3:
        x[i]=xt[i]
        print('f')
    else:
        x[i]=x[i-1]
        print('s')

    print(x[i], delta(R1,R2), i)

I appreciate your help.


Solution

  • The code works for x because the if/else block in the lower part updates x to include a value for x[i] (which will be checked on the next iteration as x[i-1]). There's no such update to the y dict, so on the second pass, y[i-1] is not available.

    You probably need to add lines like y[i]=yt[i], either in the existing if/else blocks, or in an equivalent one that has it's own logic.