php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #74665 Floats sum return quirk
Submitted: 2017-05-27 17:52 UTC Modified: 2017-05-27 20:12 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:0 (0.0%)
Same OS:1 (100.0%)
From: tomasz dot kane at gmail dot com Assigned:
Status: Not a bug Package: Variables related
PHP Version: 7.1.5 OS: Kubuntu
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: tomasz dot kane at gmail dot com
New email:
PHP Version: OS:

 

 [2017-05-27 17:52 UTC] 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

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-05-27 18:16 UTC] jhdxr@php.net
-Status: Open +Status: Not a bug
 [2017-05-27 18:16 UTC] 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 18:18 UTC] 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 20:12 UTC] 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-28 09:19 UTC] 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-28 11:31 UTC] tomasz dot kane at gmail dot com
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.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Dec 26 15:01:32 2024 UTC