Last active
July 21, 2019 05:02
-
-
Save estysdesu/e94e023619dc2ab3f2f6d5f39c6a15fd to your computer and use it in GitHub Desktop.
[Python: Numpy n-th gradient (recursion)] #numpy #gradient #slope #recursion #np
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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