Thanks to visit codestin.com
Credit goes to github.com

Skip to content

gh-103172: Add π to the math module #103178

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion Modules/mathmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -3948,6 +3948,30 @@ math_ulp_impl(PyObject *module, double x)
return x2 - x;
}

/*
Future-proof pi in case we ever move away from IEEE 754. Import time is
increased, but the added robustness makes this an acceptable trade-off.

TODO: Slightly better algorithms are known.
*/
static double
math_calc_pi(void)
{
double pi = 0.0;

for (int n = 0; ; ++n) {
double term = 4.0 / ((double) (2*n + 1));
if (n & 1)
term = -term;
double next_pi = pi + term;
if (next_pi == pi)
break;
pi = next_pi;
}

return pi;
}

static int
math_exec(PyObject *module)
{
Expand All @@ -3965,7 +3989,7 @@ math_exec(PyObject *module)
if (state->str___trunc__ == NULL) {
return -1;
}
if (PyModule_AddObject(module, "pi", PyFloat_FromDouble(Py_MATH_PI)) < 0) {
if (PyModule_AddObject(module, "π", PyFloat_FromDouble(math_calc_pi())) < 0) {
return -1;
}
if (PyModule_AddObject(module, "e", PyFloat_FromDouble(Py_MATH_E)) < 0) {
Expand Down