Java 的 Math.Pow() 函数返回令人困惑的结果
我正在使用 Math.pow() 函数,并具有以下代码:
double monthlyRate = (0.7d / 12);
int loanLength = 3;
double powerTest = Math.pow(1.00583, 36);
double powerResult = Math.pow((1 + monthlyRate),(loanLength * 12));
当通过调试器运行该函数时,值变为
powerTest => 1.2327785029794363
powerResult => 7.698552870922063
第一个是正确的。我已经在两条赋值线上进入了 Math.pow 函数。对于功率测试, Math.pow 的参数是 双a => 1.00583 双b => 36.0
对于 powerResult,它们是 双a => 1.0058333333333333 双b => 36.0
我知道这是机器执行浮点数学方式的问题,我只是不确定如何纠正它。在计算之前我尝试执行以下操作,但结果不佳:
monthlyRate = Math.round(monthlyRate * 1000) / 1000;
I am working with the Math.pow() function, and have the following code:
double monthlyRate = (0.7d / 12);
int loanLength = 3;
double powerTest = Math.pow(1.00583, 36);
double powerResult = Math.pow((1 + monthlyRate),(loanLength * 12));
When this is run through the debugger, the values become
powerTest => 1.2327785029794363
powerResult => 7.698552870922063
The first is the correct one. I've stepped into the Math.pow function on both of the assignment lines. For powerTest,
the parameters for Math.pow are
double a => 1.00583
double b => 36.0
For powerResult, they are
double a => 1.0058333333333333
double b => 36.0
I know that this is an issue with the way floating point math is performed by the machine, I'm just not sure how to correct it. I tried doing the following before the calculation with poor results:
monthlyRate = Math.round(monthlyRate * 1000) / 1000;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
1 + MonthRate
是1.0583...
,而不是1.00583
。1 + monthlyRate
is1.0583...
, not1.00583
.您的表达式 0.7d/12 = 0.0583,在 powerTest 表达式中您使用的是 0.00583。
Your expression 0.7d/12 = 0.0583, in the powerTest expression you are using 0.00583.
我认为部分问题在于
0.7/12 ~ 0.058333
和1.0583 > 。 1.00583
。我敢打赌,这是差异的真正根源,浮点调整与之无关。I think part of the problem is that
0.7/12 ~ 0.058333
, and1.0583 > 1.00583
. My bet is this is the true source of your discrepancy, the floating point adjustments have little to do with it.显然,结果(1.23...和7.70)中如此大的差异与浮点数的编码方式无关,但不仅仅是您在某处犯了错误
1+0.7/12 = 1.0583 与 1.00583 不同;-)。
Obviously a such big difference in the resut(1.23... and 7.70) is not related to the way floats are coded but more than you made a mistake somewhere
1+0.7/12 = 1.0583 is different from 1.00583 ;-).
您正在使用整数除法。
You were using integer division.
在 Java 上,您可以使用 BigDecimal 来执行货币操作,得到准确的数字:这是 Sun/Oracle 推荐的存储货币的方式数字。
On Java you can use BigDecimal to perform money operations resulting on accurate numbers: it is the Sun/Oracle recommended way to store money numbers.