Double calculation producing odd result [duplicate

2019-01-03 10:53发布

This question already has an answer here:

I have 2 numbers stored as Double, 1.4300 and 1.4350. When I subtract 1.4350 - 1.4300, it gives me the result: 0.0050000000000001155. Why does it add 1155 to the end and how can I solve this so that it returns 0.005 or 0.0050? I'm not sure rounding will work as I'm working with 2 and 4 decimal numbers.

3条回答
Animai°情兽
2楼-- · 2019-01-03 11:40

This is a common pitfall with some computer representations of fractional numbers, see this question or google for floating point precision.

查看更多
Emotional °昔
3楼-- · 2019-01-03 11:47

Oh, I love these... these are caused by inaccuracy in the double representation and floating-point arithmetic is full of these. It is often caused by recurring numbers in binary (i.e. base-2 floating-point representation). For example, in decimal 1/3 = 0.3333' In binary 1/10 is a recurring number, which means it cannot be perfectly represented. Try this: 1 - 0.1 - 0.1 - 0.1 - 0.1. You wont get 0.6 :-)

To solve this, use BigDecimal (preferred) or manipulating the double by first multiplying it something like 10000, then rounding it and then dividing it again (less clean).

Good question... it has caused huge problems in the past. Missiles overshooting targets, satellites crashing after launch, etc. Search the web for some, you'll be amazed!

查看更多
淡お忘
4楼-- · 2019-01-03 11:48

Double is not the right type for very precision floating point calculations, if you want exact results you have to use BigDecimal.

查看更多
登录 后发表回答