stella
stella

Reputation: 2596

Float arithemtic and double precision?

I was confused by the difference between float and double. I read this post. I thought the the difference is just in precision. So I expected that if 0.1 + 0.2 == 0.3 returns false then either does 0.1f + 0.2f == 0.3f.

But actually 0.1f + 0.2f == 0.3f returns true. Why that?

Is that a pure Java issue or what?

Upvotes: 2

Views: 214

Answers (2)

Simon Byrne
Simon Byrne

Reputation: 7864

No, it's just an artifact of the decimal-binary conversion.

Under the hood, floating point numbers are represented in binary. The number 0.1 can't be represented exactly in binary, so it needs to be rounded to the nearest representable number, of which the float is:

0.100000001490116119384765625

and the double is:

0.1000000000000000055511151231257827021181583404541015625

So it turns out that if you add the double nearest 0.1, and the double nearest 0.2, then round that result to the nearest double, you don't actually get the double nearest 0.3, but instead you get the one after it (which is typically printed as 0.30000000000000004, but actually has a lot more digits), hence the lack of equality.

On the other hand, if you add the float nearest 0.1, and the float nearest 0.2, then round that result to the nearest float, you do get the float nearest 0.3, hence the equality.

Upvotes: 6

Oday
Oday

Reputation: 72

You shouldn't ever compare floats or doubles for equality, you can't really guarantee that the number you assign to the float or double is exact

Upvotes: 1

Related Questions