0

I'm trying to perform a power calculation in Java for exponent that is less than 1, for example: (2^0.333) but when i calculate that in Java, i got a result with less precision than if i do the same calculation on a normal calculator.

in Java

double f = Math.pow(2.0,0.333);
System.out.println(f);

//output
//1.2596299799473993

in a normal calculator i got

//output
//1.2596299799473993502546921425703

how can I get the same result in java without losing precision?

any help is appreciated

shamary
  • 13
  • 1

4 Answers4

3

Built-in floating point arithmetic in Java is of limited precision. The built-in BigDecimal class doesn't provide the operations that you need (real exponentiation, or even logs). You can use a third-party app such as Apfloat (see the ApfloatMath class) or JScience, both of which can do the exponentiation calculation to arbitrary precision.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
1

A more precise value cannot be acquired with primitive doubles alone. Instead, use BigDecimal, which is used to represent arbitrarily precise floating-point values.

Note that you will need a custom pow function to handle BigDecimal. One implementation can be found in this SO answer.

Community
  • 1
  • 1
FThompson
  • 28,352
  • 13
  • 60
  • 93
  • This isn't very useful. How would you propose doing exponentiation of two `BigDecimal` quantities? – Ted Hopp Oct 25 '12 at 00:33
  • @TedHopp I actually began writing a method `pow(BigDecimal val, double exponent, int precision)` before realizing that wouldn't work. I'm researching how to do so reasonably. EDIT: Found one. – FThompson Oct 25 '12 at 00:34
0

A double-precision floating point value, like the one you're using in your Java code, can only accurately represent 15 to 17 significant digits. Unless the Windows calculator app you're using is using a higher-precision data type internally (which is unlikely), those digits are likely to be meaningless.

0

You can try use BigDecimal and set precision.

   BigDecimal base = new BigDecimal(2.0);

   BigDecimal exp = new BigDecimal(0.3333);

   BigDecimal resul = new BigDecimal((Math.pow(base.doubleValue(),exp.doubleValue()))).setScale(31,RoundingMode.HALF_UP);
    System.out.println("resul "+ resul);