Bug #51518 [Bgs]: should add to zero, but gets 1.1102230246252E-16 instead
| From: | rasmus@php.net | Date: | Fri, 09 Apr 2010 03:12:28 +0000 |
| Subject: | Bug #51518 [Bgs]: should add to zero, but gets 1.1102230246252E-16 instead | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-149432@lists.php.net to get a copy of this message | ||
Edit report at http://bugs.php.net/bug.php?id=51518&edit=1
ID: 51518
Updated by: rasmus@php.net
Reported by: krenshala at koboldi dot net
Summary: should add to zero, but gets 1.1102230246252E-16
instead
Status: Bogus
Type: Bug
Package: Math related
Operating System: Multiple
PHP Version: 5.2.13
New Comment:
The fix here is to decide on your precision and do:
$output = round(0.9 + ($input * 0.3), 2); // 2-decimal precision
Previous Comments:
------------------------------------------------------------------------
[2010-04-09 05:05:12] rasmus@php.net
Floating point values have a limited precision. Hence a value might
not have the same string representation after any processing. That also
includes writing a floating point value in your script and directly
printing it without any mathematical operations.
If you would like to know more about "floats" and what IEEE
754 is, read this:
http://docs.sun.com/source/806-3568/ncg_goldberg.html
Thank you for your interest in PHP.
.
------------------------------------------------------------------------
[2010-04-09 05:03:27] 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
------------------------------------------------------------------------
--
Edit this bug report at http://bugs.php.net/bug.php?id=51518&edit=1