• Post Reply Bookmark Topic Watch Topic
  • New Topic

Math.pow() returning unusual results  RSS feed

 
Ranajoy Saha
Ranch Hand
Posts: 105
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ranajoy Saha
Ranch Hand
Posts: 105
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all for clearing my doubt and rectifying my concept about precision of double and float type.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!