Ask Your Question
1

problem with float not equals but should be equals? problem

asked 2021-05-25 19:52:28 +0100

Miroslaw gravatar image

Dear Collegues

I have a problem with checking equals float numbers: code:

d = 0.2
u = d - 1
up = d - 0.5
r = u

for i in range(1,7):
    r = r + 0.1
    print(i,r,up)
    if r == up :
        print("equal","r",r,"=","up",up)
        break;

output:

1 -0.700000000000000 -0.300000000000000
2 -0.600000000000000 -0.300000000000000
3 -0.500000000000000 -0.300000000000000
4 -0.400000000000000 -0.300000000000000
5 -0.300000000000000 -0.300000000000000
6 -0.200000000000000 -0.300000000000000

in line 5 -> it should print that are equals... what is wrong?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-05-25 20:23:15 +0100

tmonteil gravatar image

If you replace print(i,r,up) with print(i,r-up) you will get:

1 -0.400000000000000
2 -0.300000000000000
3 -0.200000000000000
4 -0.100000000000000
5 -1.66533453693773e-16
6 0.0999999999999998

So, as you can see, the two floating-point numbers are not equal and differ by something very small.

The reason is that 0.1 looks exact in base 10, but in base 2 this number takes infinitely many digits. As floating-point numbers have finite precision, the representation of 0.1 is base 2 is only approximate, see:

sage: (0.1).exact_rational()
3602879701896397/36028797018963968
sage: (0.1).sign_mantissa_exponent()
(1, 7205759403792794, -56)

To provide more hints (like using rational numbers, real balls, etc), we need to know more about your objective.

edit flag offensive delete link more

Comments

yes, but please change value d to new value : d = 0.575 and my code works... I don't undestand...

Miroslaw gravatar imageMiroslaw ( 2021-05-25 20:27:51 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2021-05-25 19:52:28 +0100

Seen: 239 times

Last updated: May 25 '21