gmaster
gmaster

Reputation: 692

Java Math.pow issue

I am working on a program which needs to cube a number. Long story short, I need to compare the number to a string, so I need to get rid of the decimal place a double gives when I convert to string. To do this, I used Math.round and saved it as a long. This works fine for relatively normal numbers, but the numbers can go up to 999,999.

I used 275393 (a given test number, so I'm assuming it must be correct for the problem I'm working on) and neither a calculator nor the computer seemed to get the correct answer. The correct answer is supposed to contain 123457 somewhere in the results, but the calculator has 12346 (which I think is just rounding, as it stops listing numbers after this) and the computer has 123456 (the computer stops listing numbers after this point). Is rounding it giving it the problem (it shouldn't because I'm pretty sure it only rounds to the tenths place, but who knows)? Or is it something else?

Upvotes: 0

Views: 1994

Answers (3)

Andrew Thompson
Andrew Thompson

Reputation: 168825

I need to compare the number to a string, so I need to get rid of the decimal place a double gives when I convert to string.

Do it the other way around. Convert the String to a number, then compare it to the double (with a small tolerance to account for inaccurate binary representations of float point numbers).

Upvotes: 1

Michael Borgwardt
Michael Borgwardt

Reputation: 346327

A double has limited precision. Instead, use BigInteger or BigDecimal for your calculation.

Upvotes: 3

Nayuki
Nayuki

Reputation: 18533

Math.pow() takes two doubles and returns a double. There is not enough precision in a double to represent 2753933 = 20886164356123457 (exact).

The solution is to use BigInteger.pow().

Upvotes: 6

Related Questions