Note
Go to the end to download the full example code.
Shamrock math derivatives functions#
This example shows how to use Shamrock math derivatives functions
9 from math import *
10
11 import matplotlib.pyplot as plt
12 import numpy as np
13 from shamrock.math import *
14
15 import shamrock
Use shamrock documentation style for matplotlib
20 shamrock.matplotlib.set_shamrock_mpl_style()
Compute the error associated to a derivative function
27 def err_plot(deriv_func, x, f, df, label):
28 h = np.logspace(-16, 0, 100)
29 err = []
30
31 for i in range(len(h)):
32 _err = deriv_func(x, h[i], f) - df(x)
33 err.append(fabs(_err))
34 plt.plot(h, err, "o", label=label)
35
36
37 def analysis(f, df, x0, label):
38 plt.figure()
39
40 # fmt: off
41 err_plot(deriv_func=derivative_upwind, x=x0, f=f, df=df, label="derivative_upwind")
42 err_plot(deriv_func=derivative_centered, x=x0, f=f, df=df, label="derivative_centered")
43 err_plot(deriv_func=derivative_3point_forward, x=x0, f=f, df=df, label="derivative_3point_forward")
44 err_plot(deriv_func=derivative_3point_backward, x=x0, f=f, df=df, label="derivative_3point_backward")
45 err_plot(deriv_func=derivative_5point_midpoint, x=x0, f=f, df=df, label="derivative_5point_midpoint")
46 # fmt: on
47
48 plt.xscale("log")
49 plt.yscale("log")
50
51 ymin, ymax = plt.gca().get_ylim()
52 plt.ylim(ymin, ymax)
53
54 for i in range(1, 4):
55 print(i, estim_deriv_step(i))
56 plt.vlines(estim_deriv_step(i), 1e-50, 1e50, color="grey", alpha=0.3)
57
58 plt.xlabel("h")
59 plt.ylabel("error")
60 plt.title(label)
61 plt.legend()
Example of analysis
68 def f1(x):
69 return exp(x)
70
71
72 def df1(x):
73 return exp(x)
74
75
76 analysis(f1, df1, 0, "exp(0)")
77 analysis(f1, df1, 100, "exp(100)")
78
79
80 def f2(x):
81 return sin(x**2)
82
83
84 def df2(x):
85 return cos(x**2) * 2 * x
86
87
88 analysis(f2, df2, 0, "sin(0)")
89 analysis(f2, df2, 100, "sin(100)")
90
91 plt.show()
1 1.4901161193847656e-08
2 6.055454452393344e-06
3 0.0001220703125
1 1.4901161193847656e-08
2 6.055454452393344e-06
3 0.0001220703125
1 1.4901161193847656e-08
2 6.055454452393344e-06
3 0.0001220703125
1 1.4901161193847656e-08
2 6.055454452393344e-06
3 0.0001220703125
Total running time of the script: (0 minutes 0.966 seconds)
Estimated memory usage: 159 MB



