|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #52405 Inaccurate Pi calculation
Submitted: 2010-07-22 15:44 UTC Modified: 2010-07-22 16:15 UTC
From: chrisbabar at hotmail dot com Assigned:
Status: Not a bug Package: *Math Functions
PHP Version: 5.3.2 OS: Ubuntu 10.04 LTS
Private report: No CVE-ID: None
 [2010-07-22 15:44 UTC] chrisbabar at hotmail dot com
PHP seems to calculate pi incorrectly after 15 decimal places when calling the pi() function. I have used as a reference for the correct value of pi.

Test script:

ini_set("precision", 24);

echo pi();


Expected result:

Actual result:


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2010-07-22 15:50 UTC]
-Status: Open +Status: Bogus
 [2010-07-22 15:50 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.

 [2010-07-22 16:04 UTC] chrisbabar at hotmail dot com
I think I understand what you are saying - however this is essentially the same problem - without any float to string processing:

// Outputs bool(true)
var_dump(3.14159265358979311599796 === 3.14159265358979323846264);

And if this is expected because of the limitations with the precision - should the precision of PHP be limited to 15 decimal places?
 [2010-07-22 16:15 UTC]
Sorry, I was being a bit slack: we get enough floating point questions that my first comment's actually a canned answer. :)

You're exactly right: it's just that floating point values don't have enough precision to go beyond a certain point -- the float page in the manual says it's usually about 14 decimal digits, which lines up almost exactly with what you've just tested.

As for whether PHP should be limited, it's basically a reality of current computing that decimal values are represented as floating point values with limited precision -- fixed point arithmetic would potentially be more accurate, but much, much slower, since you'd no longer be getting any help from the hardware FPU, and for most purposes, 64-bit floating point values are good enough.
 [2010-07-22 16:23 UTC] chrisbabar at hotmail dot com
Haha, unfortunately I'm sure I won't be the last to ask about floating point values!

Thanks very much for clearing this up.
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Tue Jan 19 22:01:23 2021 UTC