8
8
9
9
"""
10
10
11
- from collections .abc import Iterator
11
+ from collections .abc import Callable , Iterator
12
12
13
13
14
- def method_1 (boundary : list [float ], steps : int ) -> float :
14
+ def method_1 (f : Callable [[ float ], float ], boundary : list [float ], steps : int ) -> float :
15
15
"""
16
16
"extended trapezoidal rule"
17
17
int(f) = dx/2 * (f1 + 2f2 + ... + fn)
18
18
19
- >>> def f (x): return x ** 2
20
- >>> abs(method_1([0, 1], 10) - 0.335) < 1e-9
19
+ >>> def func (x): return x ** 2
20
+ >>> abs(method_1(func, [0, 1], 10) - 0.335) < 1e-9
21
21
True
22
22
23
- >>> def f (x): return 1
24
- >>> abs(method_1([0, 10], 100) - 333.35 ) < 1e-9
23
+ >>> def func (x): return 1
24
+ >>> abs(method_1(func, [0, 10], 100) - 10.0 ) < 1e-9
25
25
True
26
26
27
- >>> def f (x): return x
28
- >>> method_1([0, 1], 1)
27
+ >>> def func (x): return x
28
+ >>> method_1(func, [0, 1], 1)
29
29
0.5
30
30
31
- >>> def f(x): return x ** 2
32
- >>> method_1([], 10) # Empty boundary list
31
+ >>> method_1(func, [], 10) # Empty boundary list
33
32
Traceback (most recent call last):
34
33
...
35
34
IndexError: list index out of range
36
35
37
- >>> method_1([0, 1], 0) # Steps as zero
36
+ >>> method_1(func, [0, 1], 0) # Steps as zero
38
37
Traceback (most recent call last):
39
38
...
40
39
ZeroDivisionError: division by zero
41
- >>> method_1(['0', '1'], 10) # Boundary values as strings
40
+ >>> method_1(func, ['0', '1'], 10) # Boundary values as strings
42
41
Traceback (most recent call last):
43
42
...
44
43
TypeError: unsupported operand type(s) for -: 'str' and 'str'
@@ -47,6 +46,7 @@ def method_1(boundary: list[float], steps: int) -> float:
47
46
- boundary (list of float): A two-element list specifying the lower and upper bounds
48
47
of the integration interval.
49
48
- steps (int): The number of steps (trapezoids) to divide the interval into.
49
+ - f (Callable[[float], float]): The function to be integrated.
50
50
51
51
Returns:
52
52
- float: The estimated value of the integral over the specified interval.
@@ -96,14 +96,6 @@ def make_points(a: float, b: float, h: float) -> Iterator[float]:
96
96
x = x + h
97
97
98
98
99
- def f (x : float ) -> float :
100
- """
101
- Replace this function with any specific function you need to integrate.
102
- """
103
- y = (x - 0 ) * (x - 0 )
104
- return y
105
-
106
-
107
99
if __name__ == "__main__" :
108
100
import doctest
109
101
0 commit comments