2

What are good alternatives to Math.pow and Math.sqrt? I'm looking for something a little more accurate. Usually these are accurate enough, however when I put a double through the algorithm I'm using, the returned value is just slightly false. I did the math by hand, and did each step-by-step calculation inside the algorithm using java, and I discovered that the problem lied within the innacuracy of the Math.pow and Math.sqrt methods.

I was fooling around with the BigDecimal class but I'm not sure about it's use here.

I rechecked it, It's the Double value that is too imprecise. Is there any Math method equivalents for the BigDecimal class?

user1780932
  • 81
  • 1
  • 7
  • 5
    Are you sure it's not the precision in double that's causing the imprecision in your algorithm? – Roddy of the Frozen Peas Nov 10 '12 at 15:19
  • 1
    The innacuracy is not from `Math#pow` nor `Math.sqrt` but from Java `double` precision: [Java double precision sum trouble](http://stackoverflow.com/q/10786587/1065197) – Luiggi Mendoza Nov 10 '12 at 15:20
  • 2
    Any specific example of inaccurate calculation? What precision are you after? – Bruno Nov 10 '12 at 15:21
  • 2
    You cannot achieve perfect accuracy with a double, or with any floating point form. –  Nov 10 '12 at 15:21
  • @woodchips, in addition, since sqrt(2) (for example) is an irrational number, you'll always have trouble trying to make it fit with perfect precision in a finite amount of bits or even a finite amount of ink and paper in any base... – Bruno Nov 10 '12 at 15:23
  • hmm I see what you're saying. That could very easily be the case. But in that case, is there a way for me to find sqrt, to square, to find the arcSin, etc...with BigDecimal values? – user1780932 Nov 10 '12 at 15:31
  • 1
    Convert the number to BigDecimal, then do your computations. If you then convert back to double though, again you have truncation issues, losing what you have gained. And BigDecimal still has limits, just tinier ones. –  Nov 10 '12 at 15:37
  • For sqrt, check if [this link](http://stackoverflow.com/questions/1384919/are-there-libraries-for-square-root-over-bigdecimal) is useful for you. – Federico Cristina Nov 10 '12 at 15:50

1 Answers1

1

You should have a look at this answer for increased Math.pow accuracy with BigDescimal

Community
  • 1
  • 1
Bruland
  • 13
  • 3