Skip to content

Commit 20d41f1

Browse files
vstinnerskirpichev
andcommitted
gh-131032: Fix math.fma(x, y, z) zero sign
Fix result sign when z is zero. Co-Authored-by: Sergey B Kirpichev <[email protected]>
1 parent 48cca72 commit 20d41f1

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

Lib/test/test_math.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2765,12 +2765,6 @@ def test_fma_infinities(self):
27652765
self.assertEqual(math.fma(-b, -math.inf, c), math.inf)
27662766
self.assertEqual(math.fma(-b, math.inf, c), -math.inf)
27672767

2768-
# gh-73468: On some platforms, libc fma() doesn't implement IEE 754-2008
2769-
# properly: it doesn't use the right sign when the result is zero.
2770-
@unittest.skipIf(
2771-
sys.platform.startswith(("freebsd", "wasi", "netbsd", "emscripten"))
2772-
or (sys.platform == "android" and platform.machine() == "x86_64"),
2773-
f"this platform doesn't implement IEE 754-2008 properly")
27742768
def test_fma_zero_result(self):
27752769
nonnegative_finites = [0.0, 1e-300, 2.3, 1e300]
27762770

Modules/mathmodule.c

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2344,7 +2344,22 @@ static PyObject *
23442344
math_fma_impl(PyObject *module, double x, double y, double z)
23452345
/*[clinic end generated code: output=4fc8626dbc278d17 input=e3ad1f4a4c89626e]*/
23462346
{
2347-
double r = fma(x, y, z);
2347+
double r;
2348+
if (z) {
2349+
r = fma(x, y, z);
2350+
}
2351+
else {
2352+
// gh-73468, gh-131032: On some platforms (ex: WASI, NetBSD,
2353+
// Emscripten, musl C library), libc fma() doesn't implement
2354+
// IEEE 754-2008 properly: it doesn't use the right sign when the
2355+
// result is zero.
2356+
if (x && y) {
2357+
r = x * y;
2358+
}
2359+
else {
2360+
r = copysign(1, z) == 1 ? x*y + z : x*y;
2361+
}
2362+
}
23482363

23492364
/* Fast path: if we got a finite result, we're done. */
23502365
if (isfinite(r)) {

0 commit comments

Comments
 (0)