php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #79185 sum numbers expecting to return 0
Submitted: 2020-01-28 18:29 UTC Modified: 2020-01-28 19:53 UTC
From: marius dot veleanu at gmail dot com Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 7.3.14 OS: macOS Catalina 10.15.2
Private report: No CVE-ID: None
 [2020-01-28 18:29 UTC] marius dot veleanu at gmail dot com
Description:
------------
the sum of the numbers (positive and negative) in a loop, is expected to be 0

tested with:
PHP 7.3.12-1
PHP 7.0.33-0 (cli) 
PHP 7.3.9 (cli) 

Test script:
---------------
$arr = [1.9, 1.9, 1.9, -5.7]; or  $arr = [1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, -15.2]; or  $arr = [1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, -22.8];
echo array_sum($arr);  //-8.8817841970013E-16  //1.7763568394003E-15  //-3.5527136788005E-15

AND same result with
$total = 0; foreach( $arr as $a ){ $total += $a; } echo $total;  // -8.8817841970013E-16  //1.7763568394003E-15  //-3.5527136788005E-15



BUT this works
$arr = [1.9, 1.9, -3.8];  //0
$arr = [1.9, 1.9, 1.9, 1.9, -7.6];  //0
$arr = [1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, 1.9, -17.1];  //0


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-01-28 19:53 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2020-01-28 19:53 UTC] requinix@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.


 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Nov 10 16:01:28 2024 UTC