Double calculation producing odd result [duplicate]

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!

Leave a Comment