0

感谢堆栈,我了解了浮点不精度,所以我转到了 bc 函数。

这在“普通”浮点数上效果很好,但是对于非常小的浮点数,比如10^-10类型,bcadd总是给出0.

有人可以告诉我我做错了什么来使这些小花车精确添加吗?

提前谢谢了!


PHP

$numerator = 1;
$denominator = 1000000000;
$quotientOne = $numerator / $denominator;

$numerator = 1;
$denominator = 1000000000000000;
$quotientTwo = $numerator / $denominator;

$smallSum = bcadd($quotientOne, $quotientTwo, 100);

echo $quotientOne . "<br>";
echo $quotientTwo . "<br>";
echo $smallSum . "<br>";

1.0E-9
1.0E-15
0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
4

1 回答 1

3

/运算符返回浮点数或整数它干扰了您正确使用 bcadd() 的尝试。在 bcadd() 有机会展示它的东西之前,浮点算术的局限性就会出现。

echo gettype($numerator / $denominator);
double

改为使用bcdiv()。请注意,bc*() 函数将字符串作为其参数,并且它们也返回一个字符串。

$ cat code/php/test.php
<?php
$num_1 = 1;
$denom_1 = 1000000000;

# Cast values to string type to be crystal clear about what you're doing.
$q_1 = bcdiv((string)$num_1, (string)$denom_1, strlen($denom_1));
printf("q_1: %s\n", $q_1);

$num_2 = 1;
$denom_2 = 1000000000000000;

# php will do an implicit conversion to string anyway, though.
$q_2 = bcdiv($num_2, $denom_2, strlen($denom_2));
printf("q_2: %s\n", $q_2);

printf("sum: %s\n", bcadd($q_1, $q_2, strlen($denom_2)));
?>

$ php code/php/test.php
q_1: 0.0000000010
q_2: 0.0000000000000010
sum: 0.0000000010000010

任意精度算术本质上比浮点算术慢。这就是您为获得数十、数百或数千位精度所付出的代价。

于 2013-01-31T03:01:57.670 回答