Skip to content

Instantly share code, notes, and snippets.

@duartenina
Created September 11, 2018 16:54
Show Gist options
  • Save duartenina/01c0307d4346b4ce19170ad3f9cc3614 to your computer and use it in GitHub Desktop.
Save duartenina/01c0307d4346b4ce19170ad3f9cc3614 to your computer and use it in GitHub Desktop.
import numpy as np
from findiff import FinDiff
import matplotlib.pyplot as plt
import findiff
print(findiff.__version__)
def f(x):
return x * np.exp(-x**2)
def df_dx(x):
return np.exp(-x**2) - 2*x**2*np.exp(-x**2)
def df_dx_2(x):
return 2*np.exp(-x**2)*x*(-3 + 2*x**2)
x_fine = np.linspace(0, 10, 200)
f_fine = f(x_fine)
df_dx_exact = df_dx(x_fine)
df_dx2_exact = df_dx_2(x_fine)
x_nu = np.r_[np.linspace(0, 0.5, 3, endpoint=False), np.linspace(0.5, 1.2, 7, endpoint=False),
np.linspace(1.2, 1.9, 2, endpoint=False), np.linspace(1.9, 2.9, 5, endpoint=False),
np.linspace(2.9, 10, 3)]
f_nu = f(x_nu)
d_dx_A = FinDiff(0, 2, coords=[x_nu], acc=2)
df_dx_nu_A = d_dx_A(f_nu)
d_dx_B = FinDiff(0, x_nu, 2, acc=2)
df_dx_nu_B = d_dx_B(f_nu)
d_dx_C = FinDiff(0, 1/3, 2, coords=[x_nu], acc=2)
df_dx_nu_C = d_dx_C(f_nu)
fig = plt.figure(figsize=(8,5))
plt.plot(x_fine, df_dx2_exact, label='exact')
plt.plot(x_nu, df_dx_nu_A, 'o', label='FinDiff(0, 2, coords=[x_nu], acc=2)')
plt.plot(x_nu, df_dx_nu_B, 'o', label='FinDiff(0, x_nu, 2, acc=2)')
plt.plot(x_nu, df_dx_nu_C, 'o', label='FinDiff(0, 1/3, 2, coords=[x_nu], acc=2)')
plt.legend()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment