Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callable variable in a loop

I'm having trouble in a loop. I have a bunch of points (a 5-D space) saved in an array

Coords=[]
Coords.append(zip(x,y,z,t,w))
Coords=np.array(Coords,float)

so that I can call all coords of 1 particle by, for example

Coords[0,0]=[0.0.0.0.1.]
Coords[0,1]=[0.1,0.,0.,0.,0.9]
Coords[0,1,0]=0.1

Now, I need to calculate some properties for every particle, so I create a dicionary, where for every key(i.e. every particle) I compute somwthing

A={}
Aa=np.arange(0.0,1.0+0.001,0.001)
for s in range(len(Coords[0])):
    A[s]=[]
    for a in Aa:
        if Coords[0,s,2]>=a and np.sqrt(Coords[0,s,0]*Coords[0,s,4])>=a:
            A[s].append(a)

Here I get the proper dictionary, so I'm calling the varaibles Coords[0,s,0] and Coords[0,s,4] properly, there is no problem.

Now, this is where I have problems. I need to compute another property for every particle for every value in A, therefore I create a dictionary of dictionaries.

L={}
for s in range(len(Coords[0])):
    L[s]={}
    for a in A[s]:
        L[s][a]=[]
        for i in Aa:
            if (Coords[0,s,0]-i)*(Coords[0,s,4]-i)-a**2==0:
                L[s][a].append(i)

Now I have a problem. The variables Coords are not called properly, there are missig values.

For example, the Coords[0,2,0]=0.1 and Coords[0,2,4]=0.6 should produce two values in the list: 0.1 and 0.6 (for a=0). However, in the list only appears the value 0.1, like the variable Coords[0,2,4]=0.6 doesn't exist.

However, if I write by hand the if condition like (for a=0)

if (0.1-i)*(0.6-i)-a**2==0

then I get the proper values.

Does anyone know why this is happening? Is it because I have dictionaries inside dictionaries?

Thanks.

like image 337
J.Agusti Avatar asked Aug 10 '26 07:08

J.Agusti


1 Answers

In your second condition:

(Coords[0,s,0]-i)*(Coords[0,s,4]-i)-a**2==0:

Try using a tolerance for your comparison, something like:

abs((Coords[0,s,0]-i)*(Coords[0,s,4]-i)-a**2) < 10**-10

There's a more detailed description here: Rounding errors with floats in Python using Numpy

like image 77
amckenzie Avatar answered Aug 12 '26 20:08

amckenzie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!