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 *

Compute the error associated to a derivative function

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

Exemple of analysis

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

Estimated memory usage: 159 MB

Gallery generated by Sphinx-Gallery