简体   繁体   English

Java Math.pow问题

[英]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 . 为此,我使用Math.round并将其保存为long This works fine for relatively normal numbers, but the numbers can go up to 999,999. 对于相对正常的数字,这很好用,但是数字可以达到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. 我使用了275393(给定的测试号,因此我认为它对于我正在解决的问题必须是正确的),并且计算器和计算机似乎都未获得正确的答案。 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). 正确答案应该在结果中的某处包含123457,但是计算器有12346(我认为这是四舍五入的,因为它在此之后停止列出数字),而计算机有123456(在此点之后计算机停止列出数字)。 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 . Math.pow()接受两个double并返回double There is not enough precision in a double to represent 275393 3 = 20886164356123457 (exact). double精度不够,无法表示275393 3 = 20886164356123457(精确)。

The solution is to use BigInteger.pow() . 解决方案是使用BigInteger.pow()

A double has limited precision. double精度有限。 Instead, use BigInteger or BigDecimal for your calculation. 相反,请使用BigIntegerBigDecimal进行计算。

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). String转换为数字,然后将其与double进行比较(容差较小,以解决浮点数的二进制表示形式不正确)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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