MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / method_2

Function method_2

maths/numerical_analysis/simpson_rule.py:12–58  ·  view source on GitHub ↗

Calculate the definite integral of a function using Simpson's Rule. :param boundary: A list containing the lower and upper bounds of integration. :param steps: The number of steps or resolution for the integration. :return: The approximate integral value. >>> round(method_2([0,

(boundary: list[int], steps: int)

Source from the content-addressed store, hash-verified

10
11
12def method_2(boundary: list[int], steps: int) -> float:
13 # "Simpson Rule"
14 # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)
15 """
16 Calculate the definite integral of a function using Simpson's Rule.
17 :param boundary: A list containing the lower and upper bounds of integration.
18 :param steps: The number of steps or resolution for the integration.
19 :return: The approximate integral value.
20
21 >>> round(method_2([0, 2, 4], 10), 10)
22 2.6666666667
23 >>> round(method_2([2, 0], 10), 10)
24 -0.2666666667
25 >>> round(method_2([-2, -1], 10), 10)
26 2.172
27 >>> round(method_2([0, 1], 10), 10)
28 0.3333333333
29 >>> round(method_2([0, 2], 10), 10)
30 2.6666666667
31 >>> round(method_2([0, 2], 100), 10)
32 2.5621226667
33 >>> round(method_2([0, 1], 1000), 10)
34 0.3320026653
35 >>> round(method_2([0, 2], 0), 10)
36 Traceback (most recent call last):
37 ...
38 ZeroDivisionError: Number of steps must be greater than zero
39 >>> round(method_2([0, 2], -10), 10)
40 Traceback (most recent call last):
41 ...
42 ZeroDivisionError: Number of steps must be greater than zero
43 """
44 if steps <= 0:
45 raise ZeroDivisionError("Number of steps must be greater than zero")
46
47 h = (boundary[1] - boundary[0]) / steps
48 a = boundary[0]
49 b = boundary[1]
50 x_i = make_points(a, b, h)
51 y = 0.0
52 y += (h / 3.0) * f(a)
53 cnt = 2
54 for i in x_i:
55 y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i)
56 cnt += 1
57 y += (h / 3.0) * f(b)
58 return y
59
60
61def make_points(a, b, h):

Callers 1

mainFunction · 0.85

Calls 2

make_pointsFunction · 0.70
fFunction · 0.70

Tested by

no test coverage detected