bcmath 似乎对我的计算给出了错误的答案
我不确定我做错了什么,但这个计算结果
bcscale(20);
echo bcmul(bcdiv('422218', '2388865'), '473');
与“83.599999999999999999670”相呼应,但其他每个计算器都给我83.6。
有没有办法解决这个问题还是 bcmath 的缺陷?
I am not sure what I am doing wrong but this calculation
bcscale(20);
echo bcmul(bcdiv('422218', '2388865'), '473');
echoes "83.59999999999999999670" but every other calculator gives me 83.6.
Is there a way to solve this or is it a flaw in bcmath?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您看到此结果的原因是您首先执行了除法。
除法给你:
但你要求20位,所以变成
0.1767441860465116279
。从这个角度来看, bc 现在给出了正确的结果:在这种情况下,“解决方案”将首先执行乘法(“仅”给出 9 位数字),然后执行除法:
The reason you see this result is because you first perform the division.
The division gives you:
but you ask for 20 digits, so that becomes
0.1767441860465116279
. In that light, bc gives you now the correct result:A "solution" in this case would be to first perform the multiplication (which gives you "just" 9 digits) and then the division:
bcmath 函数使用任意精度算术。计算不是 100% 精确 - 它们仅达到您要求的精确度(您要求的比例为 20)。由于计算并不精确,因此您不能总是期望答案是精确的。
你说你的计算器在这种情况下给了你正确的答案。但假设它也使用任意精度算术(大多数情况下),在其他情况下它会给你错误的答案。一些计算器通过比显示的精度更高的精度(例如额外的两位数)进行计算来隐藏其不准确性。如果您执行计算时出现错误,该错误最终会在显示屏中显示出来。
The bcmath functions use arbitrary precision arithmetic. The calculations aren't 100% precise - they're only as precise as you ask for (you asked for scale 20). Since the calculations aren't precise you can't always expect the answer to be precise.
You say that your calculator gives you the correct answer in this case. But assuming that it also uses arbitrary precision arithmetic (most do) it will give you the wrong answer in other cases. Some calculators hide their inaccuracy by calculating with a greater precision than they can display (for example an extra two digits). If you perform a calculation where the error builds up it will eventually become visible in the display.
BCMath 为您提供准确的结果。如果您需要其他数字“形式”,请使用诸如
round()
之类的函数来更改它:http://php.net/manual/en/function.round.php
例如:
会给你 83.6。
BCMath gives you exact result. If you need other number "form", use functions like
round()
to change it:http://php.net/manual/en/function.round.php
For example:
Will give you 83.6.
您指定的精度(20 位数字)超出了大多数计算器所能承受的精度。因此,他们会将其四舍五入,最有可能为 10 或 15 位数字,给出 83.5999...99,四舍五入为 83.6。
You've specified more precision (20 digits) than most calculators can carry. So they'll round it off, most likely to 10 or 15 digits, giving 83.5999...99, which rounds to 83.6.