Skip to content
Closed
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
13 changes: 11 additions & 2 deletions numpy/lib/function_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,7 @@ def gradient(f, *varargs):
[ 1. , 1. , 1. ]])]

"""
f = np.asanyarray(f)
N = len(f.shape) # number of dimensions
n = len(varargs)
if n == 0:
Expand All @@ -889,12 +890,20 @@ def gradient(f, *varargs):
slice3 = [slice(None)]*N

otype = f.dtype.char
if otype not in ['f', 'd', 'F', 'D']:
if otype not in ['f', 'd', 'F', 'D', 'm', 'M']:
otype = 'd'

# Difference of datetime64 elements results in timedelta64
if otype == 'M' :
# Need to use the full dtype name because it contains unit information
otype = f.dtype.name.replace('datetime', 'timedelta')
elif otype == 'm' :
# Needs to keep the specific units, can't be a general unit
otype = f.dtype

for axis in range(N):
# select out appropriate parts for this dimension
out = np.zeros_like(f).astype(otype)
out = np.empty_like(f, dtype=otype)
slice1[axis] = slice(1, -1)
slice2[axis] = slice(2, None)
slice3[axis] = slice(None, -2)
Expand Down
14 changes: 14 additions & 0 deletions numpy/lib/tests/test_function_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,20 @@ def test_masked(self):
x = np.ma.array([[1, 1], [3, 4]])
assert_equal(type(gradient(x)[0]), type(x))

def test_datetime64(self):
# Make sure gradient() can handle special types like datetime64
x = array(['1910-08-16', '1910-08-11', '1910-08-10', '1910-08-12',
'1910-10-12', '1910-12-12', '1912-12-12'],
dtype='datetime64[D]')
dx = array([ -5, -3, 0, 31, 61, 396, 731], dtype='timedelta64[D]')
assert_array_equal(gradient(x), dx)

def test_timedelta64(self):
# Make sure gradient() can handle special types like timedelta64
x = array([-5, -3, 10, 12, 61, 321, 300], dtype='timedelta64[D]')
dx = array([ 2, 7, 7, 25, 154, 119, -21], dtype='timedelta64[D]')
assert_array_equal(gradient(x), dx)


class TestAngle(TestCase):
def test_basic(self):
Expand Down