Skip to content

Commit 74734f7

Browse files
authored
Fast path for exact floats in math.hypot() and math.dist() (GH-8949)
1 parent 89d79b1 commit 74734f7

File tree

1 file changed

+21
-9
lines changed

1 file changed

+21
-9
lines changed

Modules/mathmodule.c

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2134,14 +2134,22 @@ math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
21342134
}
21352135
for (i=0 ; i<n ; i++) {
21362136
item = PyTuple_GET_ITEM(p, i);
2137-
px = PyFloat_AsDouble(item);
2138-
if (px == -1.0 && PyErr_Occurred()) {
2139-
goto error_exit;
2137+
if (PyFloat_CheckExact(item)) {
2138+
px = PyFloat_AS_DOUBLE(item);
2139+
} else {
2140+
px = PyFloat_AsDouble(item);
2141+
if (px == -1.0 && PyErr_Occurred()) {
2142+
goto error_exit;
2143+
}
21402144
}
21412145
item = PyTuple_GET_ITEM(q, i);
2142-
qx = PyFloat_AsDouble(item);
2143-
if (qx == -1.0 && PyErr_Occurred()) {
2144-
goto error_exit;
2146+
if (PyFloat_CheckExact(item)) {
2147+
qx = PyFloat_AS_DOUBLE(item);
2148+
} else {
2149+
qx = PyFloat_AsDouble(item);
2150+
if (qx == -1.0 && PyErr_Occurred()) {
2151+
goto error_exit;
2152+
}
21452153
}
21462154
x = fabs(px - qx);
21472155
diffs[i] = x;
@@ -2183,9 +2191,13 @@ math_hypot(PyObject *self, PyObject *args)
21832191
}
21842192
for (i=0 ; i<n ; i++) {
21852193
item = PyTuple_GET_ITEM(args, i);
2186-
x = PyFloat_AsDouble(item);
2187-
if (x == -1.0 && PyErr_Occurred()) {
2188-
goto error_exit;
2194+
if (PyFloat_CheckExact(item)) {
2195+
x = PyFloat_AS_DOUBLE(item);
2196+
} else {
2197+
x = PyFloat_AsDouble(item);
2198+
if (x == -1.0 && PyErr_Occurred()) {
2199+
goto error_exit;
2200+
}
21892201
}
21902202
x = fabs(x);
21912203
coordinates[i] = x;

0 commit comments

Comments
 (0)