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

Skip to content

bpo-37691: Let math.dist() accept sequences and iterables for coordinates #14975

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

Merged
merged 7 commits into from
Jul 27, 2019
Merged
Show file tree
Hide file tree
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
3 changes: 2 additions & 1 deletion Doc/library/math.rst
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,8 @@ Trigonometric functions
.. function:: dist(p, q)

Return the Euclidean distance between two points *p* and *q*, each
given as a tuple of coordinates. The two tuples must be the same size.
given as a sequence (or iterable) of coordinates. The two points
must have the same dimension.

Roughly equivalent to::

Expand Down
6 changes: 4 additions & 2 deletions Lib/test/test_math.py
Original file line number Diff line number Diff line change
Expand Up @@ -833,6 +833,10 @@ def testDist(self):
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
)

# Test non-tuple inputs
self.assertEqual(dist([1.0, 2.0, 3.0], [4.0, 2.0, -1.0]), 5.0)
self.assertEqual(dist(iter([1.0, 2.0, 3.0]), iter([4.0, 2.0, -1.0])), 5.0)

# Test allowable types (those with __float__)
self.assertEqual(dist((14.0, 1.0), (2.0, -4.0)), 13.0)
self.assertEqual(dist((14, 1), (2, -4)), 13)
Expand Down Expand Up @@ -873,8 +877,6 @@ class T(tuple):
dist((1, 2, 3), (4, 5, 6), (7, 8, 9))
with self.assertRaises(TypeError): # Scalars not allowed
dist(1, 2)
with self.assertRaises(TypeError): # Lists not allowed
dist([1, 2, 3], [4, 5, 6])
with self.assertRaises(TypeError): # Reject values without __float__
dist((1.1, 'string', 2.2), (1, 2, 3))
with self.assertRaises(ValueError): # Check dimension agree
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Let math.dist() accept coordinates as sequences (or iterables) rather than
just tuples.
14 changes: 3 additions & 11 deletions Modules/clinic/mathmodule.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 36 additions & 6 deletions Modules/mathmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -2427,31 +2427,49 @@ vector_norm(Py_ssize_t n, double *vec, double max, int found_nan)
/*[clinic input]
math.dist

p: object(subclass_of='&PyTuple_Type')
q: object(subclass_of='&PyTuple_Type')
p: object
q: object
/

Return the Euclidean distance between two points p and q.

The points should be specified as tuples of coordinates.
Both tuples must be the same size.
The points should be specified as sequences (or iterables) of
coordinates. Both inputs must have the same dimension.

Roughly equivalent to:
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
[clinic start generated code]*/

static PyObject *
math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
/*[clinic end generated code: output=56bd9538d06bbcfe input=937122eaa5f19272]*/
/*[clinic end generated code: output=56bd9538d06bbcfe input=74e85e1b6092e68e]*/
{
PyObject *item;
double max = 0.0;
double x, px, qx, result;
Py_ssize_t i, m, n;
int found_nan = 0;
int found_nan = 0, p_allocated = 0, q_allocated = 0;
double diffs_on_stack[NUM_STACK_ELEMS];
double *diffs = diffs_on_stack;

if (!PyTuple_Check(p)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not call just PySequence_Tuple() (which is a no-op for tuples)? This would simplify the setup and the cleanup code.

It may be also worth to use PySequence_Fast() and PySequence_Fast_GET_ITEM() in the loop. This will save you allocating a new tuple. For general iterable PySequence_Tuple() creates a list and a tuple, but PySequence_Fast() creates just a list.

But you will need to call PySequence_Fast_GET_SIZE() in a loop because list's size can be changed when you convert items to the C double.

Copy link
Contributor Author

@rhettinger rhettinger Jul 27, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't want any external function calls on the fast path for the common case.

I did try it out. The patch was shorter but it caused a 15% performance degradation:

# baseline
$ pytime -r11 -s 'from math import dist' 'dist((10.5, 12.5), (13.5, 8.5))'
5000000 loops, best of 11: 57.3 nsec per loop

# patched to always call PySequence_Tuple() and always Py_DECREF on exit
$ pytime -r11 -s 'from math import dist' -s 'p, q = (10.5, 12.5), (13.5, 8.5)' 'dist(p, q)'
5000000 loops, best of 11: 64.7 nsec per loop

p = PySequence_Tuple(p);
if (p == NULL) {
return NULL;
}
p_allocated = 1;
}
if (!PyTuple_Check(q)) {
q = PySequence_Tuple(q);
if (q == NULL) {
if (p_allocated) {
Py_DECREF(p);
}
return NULL;
}
q_allocated = 1;
}

m = PyTuple_GET_SIZE(p);
n = PyTuple_GET_SIZE(q);
if (m != n) {
Expand Down Expand Up @@ -2482,12 +2500,24 @@ math_dist_impl(PyObject *module, PyObject *p, PyObject *q)
if (diffs != diffs_on_stack) {
PyObject_Free(diffs);
}
if (p_allocated) {
Py_DECREF(p);
}
if (q_allocated) {
Py_DECREF(q);
}
return PyFloat_FromDouble(result);

error_exit:
if (diffs != diffs_on_stack) {
PyObject_Free(diffs);
}
if (p_allocated) {
Py_DECREF(p);
}
if (q_allocated) {
Py_DECREF(q);
}
return NULL;
}

Expand Down