Skip to content

Instantly share code, notes, and snippets.

@estysdesu
Last active July 21, 2019 05:02
Show Gist options
  • Save estysdesu/e94e023619dc2ab3f2f6d5f39c6a15fd to your computer and use it in GitHub Desktop.
Save estysdesu/e94e023619dc2ab3f2f6d5f39c6a15fd to your computer and use it in GitHub Desktop.
[Python: Numpy n-th gradient (recursion)] #numpy #gradient #slope #recursion #np
import numpy as np
def grad_n(y, x, n, edge_order=2):
g = np.gradient(y, x, edge_order=edge_order)
for _ in range(n-1):
g = grad_n(g, x, 1, edge_order=edge_order)
return g
import unittest
import numpy as np
class TestGrad(unittest.TestCase):
def test_grad(self):
t = np.linspace(0, 6*np.pi, 10)
y = 20*np.sin(t)
gradienter = lambda x, y: np.gradient(y, x, edge_order=1)
for i in range(5):
if i == 0:
g = gradienter(t, y)
else:
g = gradienter(t, g)
gtest = utils._grad_n(y, t, i+1, edge_order=1)
with self.subTest(self):
self.assertTrue( (gtest == g).all() )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment