Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incremented floats do not equal each other [duplicate]

Possible Duplicate:
Why can't decimal numbers be represented exactly in binary?
Program not entering if statement

So I'm trying to run a program that has two variables, when one variable is equal to another, it performs a function. In this case, printing spam. However, for some reason, when I run this program, I'm not getting any output even though I know they are equal.

g=0.0
b=3.0

while g < 30.0:
    if g==b:
        print "Hi"
    g+=.1
    print g, b
like image 311
user1541756 Avatar asked Jul 24 '12 23:07

user1541756


People also ask

Why the ID of float values are different when the same value is assigned to two different variables?

In that case the float value containing variable may contain same data but reason behind is to mathematical rules. The only two value are consider after the point & remaining are value get neglected. so the we get two different addresses of the same data containing variables.

Why do floats have rounding errors?

Because floating-point numbers have a limited number of digits, they cannot represent all real numbers accurately: when there are more digits than the format allows, the leftover ones are omitted - the number is rounded.

Why do computers mess up floating point math?

The main cause of the error in floating point division is the division algorithms used to calculate the quotient. Most computer systems calculate division using multiplication by an inverse, mainly in Z=X/Y , Z = X * (1/Y) .

Is float more accurate than double?

Double is more precise than float and can store 64 bits, double of the number of bits float can store. Double is more precise and for storing large numbers, we prefer double over float.


1 Answers

You are assuming that adding .1 enough times to 0.0 will produce 3.0. These are floating point numbers, they are inaccurate. Rounding errors make it so that the value is never exactly equal to 3.0. You should almost never use == to test floating point numbers.

like image 196
Ned Batchelder Avatar answered Oct 20 '22 20:10

Ned Batchelder