|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2010-04-09 05:03 UTC] krenshala at koboldi dot net
Description:
------------
Math error for code that should be returning zero, but instead returns 1.1102230246252E-16 on multiple systems using multiple versions of PHP.
The problem is that when the input value is -3 the output value should be zero: 0.9 + (-3 * 0.3) = 0.9 - 0.9 = 0. If the calculated value is non-zero the error does not occur.
I first saw the error on a WinXP (Home SP3, 32bit) system running PHP 5.2.9-1, but it also shows up on a MAC (10.6.2) with PHP 5.3.0 installed. I'm in the process of upgrading PHP (to 5.2.13) on my Gentoo box to test it there but haven't had a chance to do so yet.
Test script:
---------------
my_function(-3);
function my_function($input){
$output = 1;
if($input <= 0)
$output = 0.9 + ($input * 0.3);
// the above should give 0.9 - 0.9 = 0
echo "Verifying values: 0.9 - ".($input * 0.3)." is supposed to be zero?\n";
echo "Input: $input\tOutput: $output\n";
return $output;
}
Expected result:
----------------
should have received zero (0).
Actual result:
--------------
actually received: 1.1102230246252E-16
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Dec 14 04:00:01 2025 UTC |
The important thing to take away from that doc is that computers can not store fractions accurately in an efficient manner. They are much better and faster at dealing with integers. In your particular example where you are using 0.3, that is one of many fractions that a computer cannot represent. It is actually stored as 0.299999999999999988897769753748434595763683319091796875 which is very close to 0.3, but if you start doing math on it and any sort of exact comparisons, it simply won't work. You can see this with this simple code: ini_set('precision',64); echo 0.3;