Shamrock math derivatives functions#

This example shows how to use Shamrock math derivatives functions

10 from math import *
11
12 import matplotlib.pyplot as plt
13 import numpy as np
14 from shamrock.math import *

Compute the error associated to a derivative function

21 def err_plot(deriv_func, x, f, df, label):
22     h = np.logspace(-16, 0, 100)
23     err = []
24
25     for i in range(len(h)):
26         _err = deriv_func(x, h[i], f) - df(x)
27         err.append(fabs(_err))
28     plt.plot(h, err, "o", label=label)
29
30
31 def analysis(f, df, x0, label):
32     plt.figure()
33
34     # fmt: off
35     err_plot(deriv_func=derivative_upwind, x=x0, f=f, df=df, label="derivative_upwind")
36     err_plot(deriv_func=derivative_centered, x=x0, f=f, df=df, label="derivative_centered")
37     err_plot(deriv_func=derivative_3point_forward, x=x0, f=f, df=df, label="derivative_3point_forward")
38     err_plot(deriv_func=derivative_3point_backward, x=x0, f=f, df=df, label="derivative_3point_backward")
39     err_plot(deriv_func=derivative_5point_midpoint, x=x0, f=f, df=df, label="derivative_5point_midpoint")
40     # fmt: on
41
42     plt.xscale("log")
43     plt.yscale("log")
44
45     ymin, ymax = plt.gca().get_ylim()
46     plt.ylim(ymin, ymax)
47
48     for i in range(1, 4):
49         print(i, estim_deriv_step(i))
50         plt.vlines(estim_deriv_step(i), 1e-50, 1e50, color="grey", alpha=0.3)
51
52     plt.xlabel("h")
53     plt.ylabel("error")
54     plt.title(label)
55     plt.legend()

Exemple of analysis

62 def f1(x):
63     return exp(x)
64
65
66 def df1(x):
67     return exp(x)
68
69
70 analysis(f1, df1, 0, "exp(0)")
71 analysis(f1, df1, 100, "exp(100)")
72
73
74 def f2(x):
75     return sin(x**2)
76
77
78 def df2(x):
79     return cos(x**2) * 2 * x
80
81
82 analysis(f2, df2, 0, "sin(0)")
83 analysis(f2, df2, 100, "sin(100)")
84
85 plt.show()
  • exp(0)
  • exp(100)
  • sin(0)
  • sin(100)
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.902 seconds)

Estimated memory usage: 113 MB

Gallery generated by Sphinx-Gallery