diff options
| author | Victor Stinner <vstinner@python.org> | 2020-01-13 12:44:35 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-01-13 12:44:35 +0100 |
| commit | 0b2ab21956fbab8eab6d064060d4544499730316 (patch) | |
| tree | cb0be30aef9fcb0cba4aee16049219d908afdc23 /Modules/mathmodule.c | |
| parent | 7ba6f18de2582755ae31888ba6a4237d96dddc48 (diff) | |
| download | cpython-git-0b2ab21956fbab8eab6d064060d4544499730316.tar.gz | |
bpo-39310: Add math.ulp(x) (GH-17965)
Add math.ulp(): return the value of the least significant bit
of a float.
Diffstat (limited to 'Modules/mathmodule.c')
| -rw-r--r-- | Modules/mathmodule.c | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/Modules/mathmodule.c b/Modules/mathmodule.c index 632a421e3b..5e8e485afd 100644 --- a/Modules/mathmodule.c +++ b/Modules/mathmodule.c @@ -3314,6 +3314,37 @@ math_nextafter_impl(PyObject *module, double x, double y) } +/*[clinic input] +math.ulp -> double + + x: double + / + +Return the value of the least significant bit of the float x. +[clinic start generated code]*/ + +static double +math_ulp_impl(PyObject *module, double x) +/*[clinic end generated code: output=f5207867a9384dd4 input=31f9bfbbe373fcaa]*/ +{ + if (Py_IS_NAN(x)) { + return x; + } + x = fabs(x); + if (Py_IS_INFINITY(x)) { + return x; + } + double inf = m_inf(); + double x2 = nextafter(x, inf); + if (Py_IS_INFINITY(x2)) { + /* special case: x is the largest positive representable float */ + x2 = nextafter(x, -inf); + return x - x2; + } + return x2 - x; +} + + static PyMethodDef math_methods[] = { {"acos", math_acos, METH_O, math_acos_doc}, {"acosh", math_acosh, METH_O, math_acosh_doc}, @@ -3366,6 +3397,7 @@ static PyMethodDef math_methods[] = { MATH_PERM_METHODDEF MATH_COMB_METHODDEF MATH_NEXTAFTER_METHODDEF + MATH_ULP_METHODDEF {NULL, NULL} /* sentinel */ }; |
