posted 3 years ago

Hi, All

Recently when solving a commercial sum by writing a program for it, I came across this abnormality when using Math.pow(). For example, suppose double x = 1.1; So, naturally it square would be 1.21. But, when feeding this value unto Math.pow() function like Math.pow(x,2), it is returning 1.2100000000000002, when the answer is 1.21 only and there is no question of precision as 1.21 is the exact answer. It may have been written down as 1.210,1.210000000,1.21000000000 because a 0 after a decimal place is an insignificant figure. But, from where does this 2 come in the answer thrown by Math.pow(). This might be a very silly question, but I am curious to enough as to know, why this happens.

Regards,

Ranajoy

Recently when solving a commercial sum by writing a program for it, I came across this abnormality when using Math.pow(). For example, suppose double x = 1.1; So, naturally it square would be 1.21. But, when feeding this value unto Math.pow() function like Math.pow(x,2), it is returning 1.2100000000000002, when the answer is 1.21 only and there is no question of precision as 1.21 is the exact answer. It may have been written down as 1.210,1.210000000,1.21000000000 because a 0 after a decimal place is an insignificant figure. But, from where does this 2 come in the answer thrown by Math.pow(). This might be a very silly question, but I am curious to enough as to know, why this happens.

Regards,

Ranajoy

posted 3 years ago

- 1

Actually, it is a question of precision - of Java's double data type. See #20 in the http://www.coderanch.com/how-to/java/JavaBeginnersFaq for a lot of information how that comes about.

If you need precise floating point arithmetic in Java, the BigDecimal class is for you.

If you need precise floating point arithmetic in Java, the BigDecimal class is for you.

posted 3 years ago

- 1

Doubles are not exact. The double value 1.1 might actually be a little bit lesser or a little bit greater than the exact value 1.1. This is a result of using fixed precision (64 bits for double, and 32 bits for float).

If you want exact results, you should use BigDecimal instead.

If you want exact results, you should use BigDecimal instead.

*The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.*

posted 3 years ago

- 1

And it has nothing to do with Math.pow(). Our cattle drive an early lesson that shows this, by simply summing up 0.1 1000 times in a loop

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors