Skip to content

ENH: Add gcd and lcm ufuncs #8774

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 4 commits into from
Dec 13, 2017
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
9 changes: 9 additions & 0 deletions doc/release/1.15.0-notes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ Highlights
New functions
=============

* `np.gcd` and `np.lcm`, to compute the greatest common divisor and least
common multiple.


Deprecations
============
Expand Down Expand Up @@ -40,6 +43,12 @@ C API changes
New Features
============

``np.gcd`` and ``np.lcm`` ufuncs added for integer and objects types
--------------------------------------------------------------------
These compute the greatest common divisor, and lowest common multiple,
respectively. These work on all the numpy integer types, as well as the
builtin arbitrary-precision `Decimal` and `long` types.


Improvements
============
Expand Down
8 changes: 8 additions & 0 deletions doc/source/reference/routines.math.rst
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,14 @@ Floating point routines
nextafter
spacing

Rational routines
-----------------
.. autosummary::
:toctree: generated/

lcm
gcd

Arithmetic operations
---------------------
.. autosummary::
Expand Down
2 changes: 2 additions & 0 deletions doc/source/reference/ufuncs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,8 @@ Math operations
square
cbrt
reciprocal
gcd
lcm

.. tip::

Expand Down
14 changes: 14 additions & 0 deletions numpy/core/code_generators/generate_umath.py
Original file line number Diff line number Diff line change
Expand Up @@ -875,6 +875,20 @@ def english_upper(s):
TypeDescription('d', None, 'd', 'di'),
TypeDescription('g', None, 'g', 'gi'),
],
),
'gcd' :
Ufunc(2, 1, Zero,
docstrings.get('numpy.core.umath.gcd'),
"PyUFunc_SimpleBinaryOperationTypeResolver",
TD(ints),
TD('O', f='npy_ObjectGCD'),
),
'lcm' :
Ufunc(2, 1, None,
Copy link
Member Author

@eric-wieser eric-wieser May 6, 2017

Choose a reason for hiding this comment

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

Got this wrong until now. The identity of gcd is 0 since by definition, gcd(a, 0) == a.

The identity for lcm is some kind of epsilon. For the integers, that epsilon is simply 1 (lcm(a, 1) = a). However, for the rationals, (ie decimal.Decimal), this is incorrect (lcm(0.2, 1) != 0.2), nor is such an epsilon really representable anyway.

docstrings.get('numpy.core.umath.lcm'),
"PyUFunc_SimpleBinaryOperationTypeResolver",
TD(ints),
TD('O', f='npy_ObjectLCM'),
)
}

Expand Down
60 changes: 60 additions & 0 deletions numpy/core/code_generators/ufunc_docstrings.py
Original file line number Diff line number Diff line change
Expand Up @@ -3679,3 +3679,63 @@ def add_newdoc(place, name, doc):
array([ 0., 1., 2., 3., 4., 5.])

""")

add_newdoc('numpy.core.umath', 'gcd',
"""
Returns the greatest common divisor of |x1| and |x2|

Parameters
----------
x1, x2 : array_like, int
Arrays of values

Returns
-------
y : ndarray or scalar
The greatest common divisor of the absolute value of the inputs

See Also
--------
lcm : The lowest common multiple

Examples
--------
>>> np.gcd(12, 20)
4
>>> np.gcd.reduce([15, 25, 35])
5
>>> np.gcd(np.arange(6), 20)
array([20, 1, 2, 1, 4, 5])

""")

add_newdoc('numpy.core.umath', 'lcm',
"""
Returns the lowest common multiple of |x1| and |x2|

Parameters
----------
x1, x2 : array_like, int
Arrays of values

Returns
-------
y : ndarray or scalar
The lowest common multiple of the absolute value of the inputs

See Also
--------
gcd : The greatest common divisor

Examples
--------
>>> np.lcm(12, 20)
60
>>> np.lcm.reduce([3, 12, 20])
60
>>> np.lcm.reduce([40, 12, 20])
120
>>> np.lcm(np.arange(6), 20)
array([ 0, 20, 20, 60, 20, 20])

""")
38 changes: 38 additions & 0 deletions numpy/core/src/npymath/npy_math_internal.h.src
Original file line number Diff line number Diff line change
Expand Up @@ -678,3 +678,41 @@ npy_divmod@c@(@type@ a, @type@ b, @type@ *modulus)
#undef DEG2RAD

/**end repeat**/

/**begin repeat
*
* #type = npy_uint, npy_ulong, npy_ulonglong#
* #c = u,ul,ull#
*/
NPY_INPLACE @type@
npy_gcd@c@(@type@ a, @type@ b)
{
@type@ c;
while (a != 0) {
c = a;
a = b%a;
b = c;
}
return b;
}

NPY_INPLACE @type@
npy_lcm@c@(@type@ a, @type@ b)
{
@type@ gcd = npy_gcd@c@(a, b);
return gcd == 0 ? 0 : a / gcd * b;
}
/**end repeat**/

/**begin repeat
*
* #type = (npy_int, npy_long, npy_longlong)*2#
* #c = (,l,ll)*2#
* #func=gcd*3,lcm*3#
*/
NPY_INPLACE @type@
npy_@func@@c@(@type@ a, @type@ b)
{
return npy_@func@u@c@(a < 0 ? -a : a, b < 0 ? -b : b);
}
/**end repeat**/
68 changes: 68 additions & 0 deletions numpy/core/src/umath/funcs.inc.src
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#include "npy_pycompat.h"
#include "npy_import.h"


/*
Expand Down Expand Up @@ -158,6 +159,73 @@ npy_ObjectLogicalNot(PyObject *i1)
}
}

static PyObject *
npy_ObjectGCD(PyObject *i1, PyObject *i2)
{
PyObject *gcd = NULL;

/* use math.gcd if available, and valid on the provided types */
#if PY_VERSION_HEX >= 0x03050000
{
static PyObject *math_gcd_func = NULL;

npy_cache_import("math", "gcd", &math_gcd_func);
if (math_gcd_func == NULL) {
return NULL;
}
gcd = PyObject_CallFunction(math_gcd_func, "OO", i1, i2);
if (gcd != NULL) {
return gcd;
}
/* silence errors, and fall back on pure-python gcd */
PyErr_Clear();
}
#endif

/* otherwise, use our internal one, written in python */
{
static PyObject *internal_gcd_func = NULL;

npy_cache_import("numpy.core._internal", "_gcd", &internal_gcd_func);
if (internal_gcd_func == NULL) {
return NULL;
}
gcd = PyObject_CallFunction(internal_gcd_func, "OO", i1, i2);
if (gcd == NULL) {
return NULL;
}
/* _gcd has some unusual behaviour regarding sign */
return PyNumber_Absolute(gcd);
}
}

static PyObject *
npy_ObjectLCM(PyObject *i1, PyObject *i2)
{
/* lcm(a, b) = abs(a // gcd(a, b) * b) */

PyObject *gcd = npy_ObjectGCD(i1, i2);
PyObject *tmp;
if(gcd == NULL) {
return NULL;
}
/* Floor divide preserves integer types - we know the division will have
* no remainder
*/
tmp = PyNumber_FloorDivide(i1, gcd);
if(tmp == NULL) {
return NULL;
}

tmp = PyNumber_Multiply(tmp, i2);
if(tmp == NULL) {
return NULL;
}

/* even though we fix gcd to be positive, we need to do it again here */
return PyNumber_Absolute(tmp);
}

/*
*****************************************************************************
** COMPLEX FUNCTIONS **
Expand Down
30 changes: 30 additions & 0 deletions numpy/core/src/umath/loops.c.src
Original file line number Diff line number Diff line change
Expand Up @@ -1041,6 +1041,7 @@ NPY_NO_EXPORT void
/**begin repeat
* #TYPE = BYTE, SHORT, INT, LONG, LONGLONG#
* #type = npy_byte, npy_short, npy_int, npy_long, npy_longlong#
* #c = ,,,l,ll#
*/

NPY_NO_EXPORT NPY_GCC_OPT_3 void
Expand Down Expand Up @@ -1132,11 +1133,26 @@ NPY_NO_EXPORT void
}
}

/**begin repeat1
* #kind = gcd, lcm#
**/
NPY_NO_EXPORT void
@TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func))
{
BINARY_LOOP {
const @type@ in1 = *(@type@ *)ip1;
const @type@ in2 = *(@type@ *)ip2;
*((@type@ *)op1) = npy_@kind@@c@(in1, in2);
}
}
/**end repeat1**/

/**end repeat**/

/**begin repeat
* #TYPE = UBYTE, USHORT, UINT, ULONG, ULONGLONG#
* #type = npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong#
* #c = u,u,u,ul,ull#
Copy link
Member

Choose a reason for hiding this comment

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

The standard codes for these are B, H, I, L and Q. Shouldn't you use those instead?

Copy link
Member Author

@eric-wieser eric-wieser Mar 23, 2017

Choose a reason for hiding this comment

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

Possibly. Although I didn't see much point implementing B, H, and I separately, because arithmetic always promotes to int in C anyway, doesn't it?

Can you link me to a file that uses these standard codes? Oh, these are the struct.pack codes, right? I was trying to write this as though it were a free C function, like labs and llabs are to abs. I guess in hindsight they use a prefix though...

Copy link
Member Author

Choose a reason for hiding this comment

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

A better example of what I was imitating might be strto{l,ll,ul,ull} from the C standard library.

Copy link
Member

Choose a reason for hiding this comment

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

...these are the struct.pack codes, right?

They are also documented in numpy; see https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#built-in-scalar-types and numpy.typecodes['Integer'], numpy.typecodes['UnsignedInteger'], etc.

*/

NPY_NO_EXPORT void
Expand Down Expand Up @@ -1204,6 +1220,20 @@ NPY_NO_EXPORT void
}
}

/**begin repeat1
* #kind = gcd, lcm#
**/
NPY_NO_EXPORT void
@TYPE@_@kind@(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func))
{
BINARY_LOOP {
const @type@ in1 = *(@type@ *)ip1;
const @type@ in2 = *(@type@ *)ip2;
*((@type@ *)op1) = npy_@kind@@c@(in1, in2);
}
}
/**end repeat1**/

/**end repeat**/

/*
Expand Down
6 changes: 6 additions & 0 deletions numpy/core/src/umath/loops.h.src
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@ NPY_NO_EXPORT void
NPY_NO_EXPORT void
@S@@TYPE@_divmod(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func));

NPY_NO_EXPORT void
@S@@TYPE@_gcd(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func));

NPY_NO_EXPORT void
@S@@TYPE@_lcm(char **args, npy_intp *dimensions, npy_intp *steps, void *NPY_UNUSED(func));

/**end repeat1**/

/**end repeat**/
Expand Down
Loading