jeudi 5 août 2021

Numpy array into if statement modifies its values

I have identified an issue in my program and I do not know how to fix it :

First, I create with the arange function an array of values x_lin from 0.014 to 0.5 with an incrementation of 0.001

After that, I compute a ratio named r1, and then thanks to an if statement I want to find the value of that ratio into the array created firstly x_lin.

However, the if statement does not work due to a modification of the values into the array of values.

Here is the code (I added some prints to show the results):

Fa = 400
C0 = 3800

r1 = round(Fa/C0,3)    
x_lin = np.arange(0.014, 0.5, 0.001)
j = 0

ligne_r1 = 0
print('xlin=',x_lin)

for j in range(0,np.size(x_lin)):

print('xlin=',x_lin[j], 'r1=',r1, x_lin[j] == r1)

if x_lin[j] == r1:
    ligne_r1 = j

As a result for x_lin I get a good array of value :

xlin= [0.014 0.015 0.016 0.017 0.018 0.019 0.02 ...]

But when x_lin goes into the if statement it becomes :

xlin= 0.014 r1= 0.105 False
xlin= 0.015 r1= 0.105 False
xlin= 0.016 r1= 0.105 False
xlin= 0.016999999999999998 r1= 0.105 False
xlin= 0.017999999999999995 r1= 0.105 False
xlin= 0.018999999999999996 r1= 0.105 False
xlin= 0.019999999999999997 r1= 0.105 False
xlin= 0.020999999999999994 r1= 0.105 False
...

Consequently, the statement never becomes true.

All my grateful thanks to the StackOverflow community.

Aucun commentaire:

Enregistrer un commentaire