php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #39464 Range function produces odd values in foreach loop
Submitted: 2006-11-10 15:25 UTC Modified: 2006-11-10 16:25 UTC
From: netnessie at gmail dot com Assigned:
Status: Not a bug Package: *Programming Data Structures
PHP Version: 5.2.0 OS: Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
12 + 36 = ?
Subscribe to this entry?

 
 [2006-11-10 15:25 UTC] netnessie at gmail dot com
Description:
------------
When you use the range function, with a range between zero and 1, incrementing by 0.05 each step, the loop produces an incorrect result when you attempt to minus the current value in the loop from 1.

As you can see below, the last element in the array is the integer 1. The script should echo the result of 1 minus 1. However, for some reason PHP treats 1-1 as -2.22044604925E-16 instead of zero.

Reproduce code:
---------------
foreach (range(0,1,0.05) as $t)
	{
	echo (1-$t).'<br />';
	}

Expected result:
----------------
1
0.95
0.9
0.85
0.8
0.75
0.7
0.65
0.6
0.55
0.5
0.45
0.4
0.35
0.3
0.25
0.2
0.15
0.1
0.05
0

Actual result:
--------------
1
0.95
0.9
0.85
0.8
0.75
0.7
0.65
0.6
0.55
0.5
0.45
0.4
0.35
0.3
0.25
0.2
0.15
0.1
0.05
-2.22044604925E-16

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-11-10 16:25 UTC] tony2001@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://docs.sun.com/source/806-3568/ncg_goldberg.html
 
Thank you for your interest in PHP.

Yes, the result of (1 - (float)1) might look like float(-2.2204460492503E-16), because that's how modern computers work with float numbers.
 
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Sat Oct 16 04:03:33 2021 UTC