Created
September 11, 2018 12:46
-
-
Save duartenina/d02791e2b3733d3e18ff829bc6e8b241 to your computer and use it in GitHub Desktop.
This file contains 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 | |
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) | |
# plt.plot(x_fine, f_fine) | |
# plt.xlabel("x") | |
# plt.ylabel("f") | |
# plt.show(block=False) | |
x1 = np.linspace(0, 10, 20) | |
x2 = np.linspace(0, 10, 100) | |
f1 = f(x1) | |
f2 = f(x2) | |
# fig = plt.figure(figsize=(16,4)) | |
# ax1 = fig.add_subplot(121) | |
# ax2 = fig.add_subplot(122) | |
# ax1.plot(x_fine, f_fine) | |
# ax2.plot(x_fine, f_fine) | |
# ax1.plot(x1, f1, 'o') | |
# ax2.plot(x2, f2, 'o') | |
# plt.show(block=False) | |
dx1 = x1[1] - x1[0] | |
dx2 = x2[1] - x2[0] | |
d_dx1 = FinDiff(0, dx1, acc=2) | |
d_dx2 = FinDiff(0, dx2) | |
df_dx1 = d_dx1(f1) | |
df_dx2 = d_dx2(f2) | |
df_dx_exact = df_dx(x_fine) | |
df_dx2_exact = df_dx_2(x_fine) | |
# fig = plt.figure(figsize=(16,4)) | |
# ax1 = fig.add_subplot(121) | |
# ax2 = fig.add_subplot(122) | |
# ax1.plot(x_fine, df_dx_exact) | |
# ax2.plot(x_fine, df_dx_exact) | |
# ax1.plot(x1, df_dx1, 'o') | |
# ax2.plot(x2, df_dx2, 'o') | |
# plt.show(block=False) | |
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) | |
# plt.figure() | |
# plt.plot(x_fine, f_fine) | |
# plt.plot(x_nu, f_nu, 'o') | |
# plt.show(block=False) | |
d_dx = FinDiff(0, 10**10, 1, coords=[x_nu], acc=2) | |
df_dx_nu = d_dx(f_nu) | |
# plt.figure() | |
# plt.plot(x_fine, df_dx_exact) | |
# plt.plot(x_nu, df_dx_nu, 'o') | |
# plt.show(block=False) | |
d_dx2 = FinDiff(0, 10**10, 2, coords=[x_nu], acc=2) | |
df_dx2_nu = d_dx2(f_nu) | |
# plt.figure() | |
# plt.plot(x_fine, df_dx2_exact) | |
# plt.plot(x_nu, df_dx2_nu, 'o') | |
# plt.show(block=True) | |
fig = plt.figure(figsize=(10,4)) | |
ax1 = fig.add_subplot(121) | |
ax2 = fig.add_subplot(122) | |
ax1.plot(x_fine, df_dx_exact) | |
ax1.plot(x_nu, df_dx_nu, 'o') | |
ax2.plot(x_fine, df_dx2_exact) | |
ax2.plot(x_nu, df_dx2_nu, 'o') | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment