diff options
Diffstat (limited to 'tutorials/module_3/ForwardFiniteDifference')
| -rw-r--r-- | tutorials/module_3/ForwardFiniteDifference | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/tutorials/module_3/ForwardFiniteDifference b/tutorials/module_3/ForwardFiniteDifference new file mode 100644 index 0000000..128bb56 --- /dev/null +++ b/tutorials/module_3/ForwardFiniteDifference @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Thu May 8 13:27:05 2025 + +@author: christian +""" +import numpy as np +import matplotlib.pyplot as plt + +# step size +h = 0.1 +# define grid +x = np.arange(0, 2*np.pi, h) +# compute function +y = np.cos(x) + +# compute vector of forward differences +forward_diff = np.diff(y)/h +# compute corresponding grid +x_diff = x[:-1:] +# compute exact solution +exact_solution = -np.sin(x_diff) + +# Plot solution +plt.figure(figsize = (12, 8)) +plt.plot(x_diff, forward_diff, '--', \ + label = 'Finite difference approximation') +plt.plot(x_diff, exact_solution, \ + label = 'Exact solution') +plt.legend() +plt.show() + +# Compute max error between +# numerical derivative and exact solution +max_error = max(abs(exact_solution - forward_diff)) +print(max_error)
\ No newline at end of file |
