MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / calc_derivative

Function calc_derivative

maths/numerical_analysis/newton_raphson.py:18–32  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

16
17
18def 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
35def newton_raphson(

Callers 1

f_derivativeFunction · 0.85

Calls 1

fFunction · 0.70

Tested by

no test coverage detected