Numpy: finding the difference between two files containing float values

I am trying to use Python to calculate the difference between two text files and print the first value and the location where they start to diverge.

I am not sure how to use loadtxt :

 import numpy as np a = np.loadtxt("path/to/file", float) b = np.loadtxt("path/to/file2", float) while np.absolute(a - b) !=0: 1 2 3 ... 

Not sure how to end this? Is the beginning right?

+1
source share
1 answer

you can use

 idx = np.where(np.abs(ab) > 1e-6)[0] firstidx = idx[0] 

to find the first index, where the values ​​in a and b differ by more than some nominal value, for example 1e-6 :

 import numpy as np a = np.loadtxt("path/to/file", float) b = np.loadtxt("path/to/file2", float) idx = np.where(np.abs(ab) > 1e-6)[0] firstidx = idx[0] print(firstidx, a[firstidx], b[firstidx]) 

Please note that when working with float, you rarely ever want to compare with equality, for example with

 np.abs(ab) == 0 

or vice versa,

 np.abs(ab) != 0 

since the error in floating point representations can lead to the fact that the values ​​of a and b will be slightly different, even if their values ​​should be exactly the same, if their values ​​were presented with infinite accuracy.

So use something like

 np.abs(ab) > 1e-6 

instead of this. (Note that you need to select a tolerance level, for example, 1e-6).


Here is a simple example demonstrating the trap of comparing floats using equality:

 In [10]: 1.2-1.0 == 0.2 Out[10]: False 
+3
source

All Articles