jurchiks
jurchiks

Reputation: 1433

float, double and int math in Java

I had some doubts/questions about the math in Java, so I made a small program a screenshot of which you can see in this link:
http://www.imageshuffle.com/view.php?filename=73doublevsfloat.jpg
How are such numbers even possible?

f / i should be 0.0155 no matter how you look at it
i * f should be 155 no matter how you look at it
i + f should be 101.55
i - f should be 98.45

etc. Same with double.
So what gives? Why is math in Java so incorrect?

Upvotes: 0

Views: 1185

Answers (1)

Nikita Rybak
Nikita Rybak

Reputation: 68006

That happens because i /= f modifies i: it's equivalent of i = i / f (plus rounding).
Thus, when you execute f / i, i is ~65 instead of 100.

Upvotes: 4

Related Questions