Java: Working with Exponentiation

I have a problem with this program where I have to calculate the base ^ expo value and the base is a real number whereas the exponent is an integer. With (95.123)^12

I expect 548815620517731830194541.899025343415715973535967221869852721

, but my program produces 548815620517732160000000.000000

, which is wrong. Please suggest a better approach.

// declare variables and read values
double myBase = scan.nextDouble(); 
int myExponent = scan.nextInt();

// display result
System.out.printf("%f", Math.pow(myBase, myExponent));

      

+3


source to share


2 answers


try using BigDecimal

Example:



BigDecimal base = new BigDecimal("some number");
int exponent = ..;

BigDecimal result = base.pow(exponent);

      

+5


source


A type double

in Java is IEEE

double and only has 53 bits of precision. Because of this, you will get the highest possible value double

for the true answer.

Due to the large magnitude of the result, the closest values ​​are double

slightly larger than 1

. You can check this by calling the method Math.ulp

(one in the last place).

System.out.println(Math.ulp(Math.pow(myBase, myExponent)));

      

Output:

6.7108864E7

      

Even with precision, the consecutive values double

are 67 million apart.



Alternatively you can use BigDecimal

for example

BigDecimal myBase= new BigDecimal(scan.next());
int myExponent= scan.nextInt();

//displays result
System.out.println(myBase.pow(myExponent));

      

Output:

548815620517731830194541.899025343415715973535967221869852721

      

Note what pow

is taking hereint

and not the other BigDecimal

.

+1


source







All Articles