Thanks to stack, I learned about floating point imprecision, so I went over to the bc functions.
That works great on “normal” floats, but with extremely small floats, say 10^-10 types, bcadd always gives 0.
Can someone show me what I’m doing wrong to make these small floats add with precision?
Many thanks in advance!
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>";
gives
1.0E-9
1.0E-15
0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
The
/operator returns either a float or an integer. It’s interfering with your attempts to use bcadd() correctly. The limitations of floating-point arithmetic will take hold before bcadd() gets a chance to show its stuff.Use
bcdiv()instead. Note that the bc*() functions take strings as their arguments, and they also return a string.Arbitrary-precision arithmetic is inherently slower than floating-point arithmetic. That’s the price you pay for dozens, hundreds, or thousands of digits of accuracy.