Win a copy of Design for the Mind this week in the Design forum!

# Double Calculations?

Deepak Borania
Ranch Hand
Posts: 45

Can you please explain to me why does the above two statements output different results?
I think it's something to do with java's representation of floats, not sure though.

Thanks

John de Michele
Rancher
Posts: 600
Deepak:

You get different results because doubles and floats are inherently imprecise. Floating point numbers on computers are approximations, and so you get the results that you did. You shouldn't use floating point numbers for applications where you need real accuracy, such as when dealing with real money. In such a case, you'd probably want to look at the BigDecimal class.

John.

Henry Wong
author
Marshal
Posts: 21003
77
I think it's something to do with java's representation of floats, not sure though.

Java respresentation of floating point is the IEEE standard -- which is the standard used by practically every modern day processor.

Henry

Campbell Ritchie
Sheriff
Posts: 48652
56
Deepak Borania wrote:I think it's something to do with java's representation of floats, not sure though.
It's because (as Henry said, like most languages) it is represented in binary. It is not possible to represent 0.1 precisely, so you get that sort of result. Try representing 1 / 3 precisely in decimal, and you will see the problem.

Deepak Borania
Ranch Hand
Posts: 45
@John : Didn't knew about BigDecimal.

Thanks guys

Rob Spoor
Sheriff
Posts: 20512
54
Computers can only count in binary. That means multiples of 2, but also multiples of 1/2: 1/4, 1/8, etc. 0.1, or 1/10, is represented as follows: 1/16 + 1/32 + 1/256 + 1/512 + 1/4096 + 1/8192 + ...
If you represent 1/2 as .1, 1/4 as .01 etc, you get the following binary representation: .0001100110011001100...
As you can see, this repeats, just like 1/3 does when represented in decimals: 0.33333333...
So you see, just as we humans just quit after a number of threes, processors quit after a while as well. That's where numbers are rounded, and you get these imperfections.

BigDecimal is designed to handle these imperfections, so if you are bothered by it use that class.

Deepak Borania
Ranch Hand
Posts: 45
yeah I'm familiar with binary representations.....i had advanced digital electronics design course in college

The accurate representation mattered in the class i was trying to create(monetary related). I got around it counting the money in cents instead.