我正在使用PHP的bcmath
库对定点数字执行操作。我本来希望得到Python的Decimal
类的相同行为,但是我很惊讶地发现以下行为:
// PHP:
$a = bcdiv('15.80', '483.49870000', 26);
$b = bcmul($a, '483.49870000', 26);
echo $b; // prints 15.79999999999999999999991853
在Python中使用Decimal
s时,我得到:
为什么?由于我使用它来执行非常敏感的操作,所以我想找到一种在PHP中获得与Python相同的结果的方法(即(x / y) * y == x
)
经过一番实验,我终于明白了。这是舍入与截断的问题。默认情况下,Python使用
ROUND_HALF_EVEN
取整,而PHP只是以指定的精度截断。Python的默认精度是28,而在PHP中使用的是26。在如果您想让Python模仿PHP的截断行为,只需更改
^{pr2}$rounding
属性:让PHP的行为像Python的默认值有点困难。我们需要为除法和乘法创建一个自定义函数,它像Python一样取整“半偶数”:
下面是一个演示:
相关问题 更多 >
编程相关推荐