开发者

What is special about this math? [duplicate]

This question already has answers here: Closed 11 years 开发者_开发知识库ago.

Possible Duplicate:

Java floating point arithmetic

What is special about this double math in Java? I would expect the answer of .9 - 1 to be -0.1, however the response is -0.09999999999999998

double a = 0.9;
double b = 1.0;
double c = a - b;
System.out.println(c);
>>-0.09999999999999998


Floating point precision is difficult for computers. See this article and Retain precision with double in Java for details

For accurate floating point arithmetic use BigDecimal


Yet another question about precision of doubles. Doubles have limited precision. Not all numbers can be represented precisely!


The value 0.9 cannot be represented exactly in binary form.


double is not exact. this is the nearest number that can be represented by double.

try to read what every programmer should know about floating point arithmetic.


There are an infinite number of numbers between any two values.

There are a finite number of memory bits on any computer. So any way we chose to represent floating point numbers will never be exact.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜