|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #64928 Summing floats yields different result when order of summands is changed
Submitted: 2013-05-27 10:22 UTC Modified: 2013-05-27 10:26 UTC
From: thz at plista dot com Assigned:
Status: Not a bug Package: Math related
PHP Version: 5.5Git-2013-05-27 (Git) OS: Ubuntu 12.04
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
Block user comment
Status: Assign to:
Bug Type:
From: thz at plista dot com
New email:
PHP Version: OS:


 [2013-05-27 10:22 UTC] thz at plista dot com
First of all: I am aware of how floats work and that they are only approximations of their ideal values.

I found an inconsistency in how they are handled when added, please see the code below. Variable $a and $b are created by summing up three floats <1.0. The only difference is the order of the summands. Both variables should have exactly the same value, yet $a evaluates to 1.0 and $b to <1.0.

Test script:

$a = array_sum(array(0.6, 0.3, 0.1));
$b = array_sum(array(0.1, 0.3, 0.6));

var_dump($a); // float(1)
var_dump($b); // float(1)
var_dump($a == $b); // bool(false)
var_dump(intval($a)); // int(0)
var_dump(intval($b)); // int(1)

$c = $a - 1;
var_dump($c); // float(-1.1102230246252E-16)

Expected result:

Actual result:


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2013-05-27 10:26 UTC]
-Status: Open +Status: Not a bug
 [2013-05-27 10:26 UTC]
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:

Thank you for your interest in PHP.

 [2013-05-27 10:38 UTC] thz at plista dot com
Thanks for the clarification, thinking about it again, I realize that this is due to rounding errors. I guess I didn't know everything about floats after all.
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Thu Feb 20 06:01:27 2020 UTC