Bug #79185 [Opn->Nab]: sum numbers expecting to return 0

From: Date: Tue, 28 Jan 2020 19:53:50 +0000
Subject: Bug #79185 [Opn->Nab]: sum numbers expecting to return 0
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-225205@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=79185&edit=1 ID: 79185 Updated by: requinix@php.net Reported by: marius dot veleanu at gmail dot com Summary: sum numbers expecting to return 0 -Status: Open +Status: Not a bug Type: Bug Package: *General Issues Operating System: macOS Catalina 10.15.2 PHP Version: 7.3.14 Block user comment: N Private report: N New Comment: 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. Previous Comments: ------------------------------------------------------------------------ [2020-01-28 18:29:56] 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 ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=79185&edit=1

« previous php.bugs (#225205) next »