Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why 7%1.4 is not zero?
#1
Hello guys,

7/1.4=5, the remainder is zero, simple maths.

But why 7%1.4 gives the result 4.440892098500626e-16?

I know it is extremely close to zero, but I want to know how Python do the maths and why it happen. 

Does anyone can help me?

p.s. I am using Python 2.7.13
Reply
#2
It's because the underlying math is done in binary. Consider 10 / 3, you can't represent it precisely with decimal notation. The same problem happens here, except that 1.4 can't be precisely in binary.

If it's a problem in your code, the typical way to solve the problem is to have a tolerance. Check that the result is sufficiently small. 10**(-16) is very small.
Reply
#3
(Mar-06-2017, 07:14 PM)micseydel Wrote: It's because the underlying math is done in binary. Consider 10 / 3, you can't represent it precisely with decimal notation. The same problem happens here, except that 1.4 can't be precisely in binary.

If it's a problem in your code, the typical way to solve the problem is to have a tolerance. Check that the result is sufficiently small. 10**(-16) is very small.

Thank you! Got it!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020