OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

python and numpy precision issue (on MacBook M3) [duplicate]

  • Thread starter Thread starter Pierre
  • Start date Start date
P

Pierre

Guest
I'm trying to understand precision issues with python, which break my code (Irrelevant to the question but I'm playing with filters).

I have same problem with numpy, with np.float32, np.float64 and np.float128

My code is also unable to work, because I can't verify equality of floats.

Code:
a = 502.02
b = 503.56
c = 1005.58

print("\n")
print(f"a={a} {type(a)}")
print(f"b={b} {type(b)}")
print(f"c={c} {type(c)}")
print(f"a+b={a+b} type {type(a+b)}")

if (a+b) != 1005.58:
    print(f"error with literal {1005.58} != {a} + {b}, type {type(1005.58)}")
if (a+b) != c:
    print(f"error with float {c} != {a} + {b}")

The output on my MacBook M3 and online python console is:

Code:
a=502.02 <class 'float'>
b=503.56 <class 'float'>
c=1005.58 <class 'float'>
a+b=1005.5799999999999 type <class 'float'>
error with literal 1005.58 != 502.02 + 503.56, type <class 'float'>
error with float 1005.58 != 502.02 + 503.56
<p>I'm trying to understand precision issues with python, which break my code (Irrelevant to the question but I'm playing with filters).</p>
<p>I have same problem with numpy, with np.float32, np.float64 and np.float128</p>
<p>My code is also unable to work, because I can't verify equality of floats.</p>
<pre><code>a = 502.02
b = 503.56
c = 1005.58

print("\n")
print(f"a={a} {type(a)}")
print(f"b={b} {type(b)}")
print(f"c={c} {type(c)}")
print(f"a+b={a+b} type {type(a+b)}")

if (a+b) != 1005.58:
print(f"error with literal {1005.58} != {a} + {b}, type {type(1005.58)}")
if (a+b) != c:
print(f"error with float {c} != {a} + {b}")
</code></pre>
<p>The output on my MacBook M3 and online python console is:</p>
<pre><code>a=502.02 <class 'float'>
b=503.56 <class 'float'>
c=1005.58 <class 'float'>
a+b=1005.5799999999999 type <class 'float'>
error with literal 1005.58 != 502.02 + 503.56, type <class 'float'>
error with float 1005.58 != 502.02 + 503.56

</code></pre>
 

Latest posts

B
Replies
0
Views
1
Blundering Ecologist
B
Top