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
15 from shamrock.math import *

Compute the error associated to a derivative function

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

Exemple of analysis

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

Estimated memory usage: 63 MB

Gallery generated by Sphinx-Gallery