Bug #74665 [Com]: Floats sum return quirk
| From: | tomasz dot kane at gmail dot com | Date: | Sun, 28 May 2017 11:32:00 +0000 |
| Subject: | Bug #74665 [Com]: Floats sum return quirk | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-209293@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=74665&edit=1
ID: 74665
Comment by: tomasz dot kane at gmail dot com
Reported by: tomasz dot kane at gmail dot com
Summary: Floats sum return quirk
Status: Not a bug
Type: Bug
Package: Variables related
Operating System: Kubuntu
PHP Version: 7.1.5
Block user comment: N
Private report: N
New Comment:
Oh, my bad, if the result should be 1 then I can expect 0,999~
In this case more reasonable is something like 0,000000000001 (for humans ;-))
I feel convinced.
Previous Comments:
------------------------------------------------------------------------
[2017-05-28 09:19:15] a at b dot c dot de
What's wrong with 2.2204460492503E-16? That's 2**-52; about as close to zero as 64-bit
IEEE754 floating point can get without actually being zero.
Why you'd expect 0.99999~ (or about roughly 1) instead is baffling.
------------------------------------------------------------------------
[2017-05-27 20:12:28] tomasz dot kane at gmail dot com
Thanks for answer, I'll use bc but...
I can accept result like: 0.99999~ but 2.2204460492503E-16 ?! Madness :-)
------------------------------------------------------------------------
[2017-05-27 18:18:56] jhdxr@php.net
you may use [bc math](http://jp2.php.net/manual/en/ref.bc.php) to get the precise result.
------------------------------------------------------------------------
[2017-05-27 18:16:19] jhdxr@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://www.floating-point-gui.de/
Thank you for your interest in PHP.
------------------------------------------------------------------------
[2017-05-27 17:52:58] tomasz dot kane at gmail dot com
Description:
------------
I'm just calculate array values sum.
BTW I know about Floating point precision, but this result...
Test script:
---------------
$foo = [2.45, -1.05, -1.40];
echo array_sum($foo); // 2.2204460492503E-16
// same result when use foreach $sum += $item
Expected result:
----------------
0
Actual result:
--------------
2.2204460492503E-16
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=74665&edit=1