Tuesday, January 2. 200781.4 is evilTrackbacks
Trackback specific URI for this entry
No Trackbacks
Comments
Display comments as
(Linear | Threaded)
As any other guy I knew about floating point precision, but I always thought that it could only lose precision in the least significant digits, numerous digits after the decimal point and that it would only happen in inextricably complicated and rare situations. Now that I've run your very small and simple snippet I'm blown off.
Thanks for sharing that insightful piece of information, now you've increased my paranoia by at least 7.105427357601E15 percents
Rounding the values kinda sorts the problem ... but yes it is really bad :/
same here:
$total = 100 - 81.3; print (18.7 - $total); or here: $total = 100 - 80.2; print (19.8 - $total); even in VB.
use the bcmath library : http://www.php.net/manual/en/ref.bc.php
<br /> $truetotal = (float) bcadd('100', '-81.4', 1);<br /> <br /> echo "18.6 == {$truetotal}? " .<br /> ($truetotal === 18.6 ? 'yes' : 'no') .<br /> "\n";<br /> <br /> var_dump(18.6 - $truetotal);<br /> output => 18.6 == 18.6? yes
If you don't have the bcmath php extension installed work out the values in cents first.
I've ported a part of the Weka Data Mining Utils class that is used in all the classes when numerical comparisons are made. It addresses your concerns by adding a tolerance factor to all comparisons.
Here is a link to the relevant blog entry: http://www.phpmath.com/home?op=perm&nid=53 Comments currently turned off as I don't have time right now to deal with spambots. |
Paying for the SiteQuicksearchCategoriesDaily Readsadam trachtenberg
Ben Ramsey Chris Shiflett Dynamically Typed (Harry Fuecks) george schlossnagle John Coggeshall John Lim Marco Tabini PHP Application Tools PHPCommunity.org Planet PHP Sebastian Bergmann Sklar The PHP WTF Tobias Schlitt Tom Sommer Wez Furlong |
