0

I read the post is-floating-point-math-broken and get Why it happens, but I couldn't find a solution that could help me..

How can I do the correct subtraction?

Python version 2.6.6, Numpy version 1.4.1.

I have two numpy.ndarray each one contain float32 values, origin and new. I'm trying to use numpy.subtract to subtract them but I get the following (odd) result:

>>> import numpy as 
>>> with open('base_R.l_BSREM_S.9.1_001.bin', 'r+') as fid:
        origin = np.fromfile(fid, np.float32)
>>> with open('new_R.l_BSREM_S.9.1_001.bin', 'r+') as fid:
        new = np.fromfile(fid, np.float32)
>>> diff = np.subtract(origin, new)
>>> origin[5184939]
0.10000000149011611938
>>> new[5184939]
0.00000000023283064365
>>> diff[5184939]
0.10000000149011611938

Also when I try to subtract the arrays at 5184939 I get the same result as diff[5184939]

>>> origin[5184939] - new[5184939]
0.10000000149011611938

But when I do the following I get this results:

>>> 0.10000000149011611938 - 0.00000000023283064365
0.10000000125728548

and that's not equal to diff[5184939]

How the right subtraction can be done? (0.10000000125728548 is the one that I need)

Please help, and Thanks in advance

Community
  • 1
  • 1
Idan.c
  • 121
  • 1
  • 1
  • 7
  • The proposed duplicate http://stackoverflow.com/questions/588004/is-floating-point-math-broken may explain why you can differing floating representations, but does not explain the difference in this case. Unduplicated. – hpaulj Aug 15 '16 at 15:41

1 Answers1

0

You might add your Python and numpy versions to the question.

Differences can arise from np.float32 v np.float64 dtype, the default Python float type, as well as display standards. numpy uses different display rounding than the underlying Python.

The subtraction itself does not differ.

I can reproduce the 0.10000000125728548 value, which may also display as 0.1 (out 8 decimals).

I'm not sure where the 0.10000000149011611938 comes from. That looks as though new[5184939] was identically 0, not just something small like 0.00000000023283064365.

hpaulj
  • 221,503
  • 14
  • 230
  • 353