Reputation:
I have a problem with this program where I have to calculate the value of base^expo, and the base is a real number whereas the exponent is an integer. With (95.123)^12
I'm expecting 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));
Upvotes: 3
Views: 456
Reputation: 1738
try to use BigDecimal
example:
BigDecimal base = new BigDecimal("some number");
int exponent = ..;
BigDecimal result = base.pow(exponent);
Upvotes: 5
Reputation: 178243
The double
type in Java is a IEEE
double and has only 53 bits of precision. Because of this, you will get the closest double
value possible to the true answer.
Because of the large magnitude of the result, the closest double
values are quite a bit more than 1
apart. You can verify this by calling the Math.ulp
method (unit in the last place).
System.out.println(Math.ulp(Math.pow(myBase, myExponent)));
This outputs:
6.7108864E7
Even with the precision, consecutive double
values are 67 million apart.
As an alternative, you can use BigDecimal
s instead, e.g.
BigDecimal myBase= new BigDecimal(scan.next());
int myExponent= scan.nextInt();
//displays result
System.out.println(myBase.pow(myExponent));
Output:
548815620517731830194541.899025343415715973535967221869852721
Note that pow
here takes an int
, not another BigDecimal
.
Upvotes: 1