Question

I am not sure what I am doing wrong but this calculation

bcscale(20);
echo bcmul(bcdiv('422218', '2388865'), '473');

echoes "83.59999999999999999670" but every other calculator gives me 83.6.

Is there a way to solve this or is it a flaw in bcmath?

Was it helpful?

Solution

The reason you see this result is because you first perform the division.

The division gives you:

422218/2388865
0.17674418604651162790697674418604651163

but you ask for 20 digits, so that becomes 0.1767441860465116279. In that light, bc gives you now the correct result:

0.1767441860465116279*473
83.5999999999999999967

A "solution" in this case would be to first perform the multiplication (which gives you "just" 9 digits) and then the division:

bcscale(20);
echo bcdiv(bcmul('422218','473'),'2388865');
83.60000000000000000000

OTHER TIPS

The bcmath functions use arbitrary precision arithmetic. The calculations aren't 100% precise - they're only as precise as you ask for (you asked for scale 20). Since the calculations aren't precise you can't always expect the answer to be precise.

You say that your calculator gives you the correct answer in this case. But assuming that it also uses arbitrary precision arithmetic (most do) it will give you the wrong answer in other cases. Some calculators hide their inaccuracy by calculating with a greater precision than they can display (for example an extra two digits). If you perform a calculation where the error builds up it will eventually become visible in the display.

BCMath gives you exact result. If you need other number "form", use functions like round() to change it:

http://php.net/manual/en/function.round.php

For example:

echo round(bcmul(bcdiv('422218', '2388865'), '473'), 1);

Will give you 83.6.

You've specified more precision (20 digits) than most calculators can carry. So they'll round it off, most likely to 10 or 15 digits, giving 83.5999...99, which rounds to 83.6.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top