php.net |  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
 [2013-05-27 10:22 UTC] thz at plista dot com
Description:
------------
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:
---------------
<?php

$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:
----------------
float(1)
float(1)
bool(true)
int(1)
int(1)
float(0)

Actual result:
--------------
float(1)
float(1)
bool(false)
int(0)
int(1)
float(-1.1102230246252E-16)

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

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


 [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 22:01:29 2020 UTC