Approximate the derivative of a function f(x) at a point x using the finite difference method >>> import math >>> tolerance = 1e-5 >>> derivative = calc_derivative(lambda x: x**2, 2) >>> math.isclose(derivative, 4, abs_tol=tolerance) True >>> derivative = calc_deriv
(f: RealFunc, x: float, delta_x: float = 1e-3)
| 16 | |
| 17 | |
| 18 | def calc_derivative(f: RealFunc, x: float, delta_x: float = 1e-3) -> float: |
| 19 | """ |
| 20 | Approximate the derivative of a function f(x) at a point x using the finite |
| 21 | difference method |
| 22 | |
| 23 | >>> import math |
| 24 | >>> tolerance = 1e-5 |
| 25 | >>> derivative = calc_derivative(lambda x: x**2, 2) |
| 26 | >>> math.isclose(derivative, 4, abs_tol=tolerance) |
| 27 | True |
| 28 | >>> derivative = calc_derivative(math.sin, 0) |
| 29 | >>> math.isclose(derivative, 1, abs_tol=tolerance) |
| 30 | True |
| 31 | """ |
| 32 | return (f(x + delta_x / 2) - f(x - delta_x / 2)) / delta_x |
| 33 | |
| 34 | |
| 35 | def newton_raphson( |