【发布时间】:2016-10-02 22:48:25
【问题描述】:
我正在使用 PHP 的 bcmath 库对定点数执行操作。我期待得到与 Python 的 Decimal 类相同的行为,但我很惊讶地发现了以下行为:
// PHP:
$a = bcdiv('15.80', '483.49870000', 26);
$b = bcmul($a, '483.49870000', 26);
echo $b; // prints 15.79999999999999999999991853
在 Python 中使用 Decimals 时,我得到:
# Python:
from decimal import Decimal
a = Decimal('15.80') / Decimal('483.49870000')
b = a * Decimal('483.49870000')
print(b) # prints 15.80000000000000000000000000
这是为什么呢?当我使用它来执行非常敏感的操作时,我想找到一种方法在 PHP 中获得与 Python 中相同的结果(即(x / y) * y == x)
【问题讨论】:
-
是:
$a = bcdiv('15.80', '483.49870000', 26); echo gettype($a);打印“字符串” -
哪个是正确的,顺便说一句?
标签: php python decimal fixed-point bcmath