Double calculation producing odd result [duplicate]
Asked Answered
P

3

4

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.

Perineurium answered 24/11, 2011 at 8:1 Comment(0)
L
14

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!

Lubricous answered 24/11, 2011 at 8:7 Comment(2)
Are you serious about the missiles and satellites? Or was that sarcasm?Panpsychist
ima.umn.edu/~arnold/455.f96/disasters.html as well as theinquirer.net/inquirer/news/1047844/… (just two I could find...)Lubricous
P
4

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

Printing answered 24/11, 2011 at 8:5 Comment(1)
+1: So, so common its surprising people don't know about it.Thrown
S
2

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

Stab answered 24/11, 2011 at 8:4 Comment(4)
No need to use BigDecimal in this case (which has a number of problems). It's enough to round appropriately on output.Syncom
@sleske: And what are the problems with BigDecimal? The only one I know about is performance.Businesswoman
@Max: Mainly performance (CPU overhead, memory usage, and extra work for the GC), and the very clunky API (no way to use operators).Syncom
@Max: There are valid uses of BigDecimal. I just wanted to point out that in a simple case like this it's not really necessary, and should thus be avoided IMHO.Syncom

© 2022 - 2024 — McMap. All rights reserved.