简体   繁体   中英

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?

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

The solution is to use BigInteger.pow() .

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM