在下面的代码中,为什么乘法方法不会产生舍入误差,而累积加法方法会产生?
function get_value() { return 26.82; }
function a($quantity) {
$value_excluding_vat = get_value();
$value_including_vat = round($value_excluding_vat * (1 + (20 / 100)),2);
$total_nett = 0;
$total_gross = 0;
for($i=0; $i<$quantity; $i++) {
$total_nett += $value_excluding_vat;
$total_gross += $value_including_vat;
}
return array(
$total_nett,
$total_gross
);
}
function b($quantity) {
$value_excluding_vat = get_value();
$value_including_vat = round($value_excluding_vat * (1 + (20 / 100)),2);
return array(
$quantity * $value_excluding_vat,
$quantity * $value_including_vat
);
}
$totals = a(1000);
print_r($totals);
echo $totals[1] - $totals[0];
echo "\n\n";
$totals = b(1000);
print_r($totals);
echo $totals[1] - $totals[0];
这是我的输出:
Array
(
[0] => 26820
[1] => 32180
)
5360.0000000005
Array
(
[0] => 26820
[1] => 32180
)
5360