user482594
user482594

Reputation: 17476

Java's Math.pow is returning off by 1 error

If I run Math.pow(15, 14) in Java, the result comes out as

29192926025390624

However, if I run 15^14 in a scientific calculator in windows, it returns

29192926025390625

Is this because Math.pow(a, b) uses double for its calculation?

If that is so, what is the best way to solve this kind of problem? (e.g. getting correct answer for 15^14 in Java)

Upvotes: 2

Views: 120

Answers (1)

Keppil
Keppil

Reputation: 46209

The rounding error is as you suspect because of the floating point arithmetic used by Math.pow(). A double can't hold the value 29192926025390625, as demonstrated by this snippet:

double d = 29192926025390625L;
System.out.println(d);

which prints

2.9192926025390624E16

You can use BigInteger to avoid rounding issues:

BigInteger b = new BigInteger("15");
BigInteger result = b.pow(14);

Upvotes: 4

Related Questions