55
66method 1:
77"extended trapezoidal rule"
8+ int(f) = dx/2 * (f1 + 2f2 + ... + fn)
89
910"""
1011
1112
1213def method_1 (boundary , steps ):
13- # "extended trapezoidal rule"
14- # int(f) = dx/2 * (f1 + 2f2 + ... + fn)
14+ """
15+ Apply the extended trapezoidal rule to approximate the integral of function f(x)
16+ over the interval defined by 'boundary' with the number of 'steps'.
17+
18+ Args:
19+ boundary (list of floats): A list containing the start and end values [a, b].
20+ steps (int): The number of steps or subintervals.
21+ Returns:
22+ float: Approximation of the integral of f(x) over [a, b].
23+ Examples:
24+ >>> method_1([0, 1], 10)
25+ 0.3349999999999999
26+ """
1527 h = (boundary [1 ] - boundary [0 ]) / steps
1628 a = boundary [0 ]
1729 b = boundary [1 ]
@@ -26,13 +38,40 @@ def method_1(boundary, steps):
2638
2739
2840def make_points (a , b , h ):
41+ """
42+ Generates points between 'a' and 'b' with step size 'h', excluding the end points.
43+ Args:
44+ a (float): Start value
45+ b (float): End value
46+ h (float): Step size
47+ Examples:
48+ >>> list(make_points(0, 10, 2.5))
49+ [2.5, 5.0, 7.5]
50+
51+ >>> list(make_points(0, 10, 2))
52+ [2, 4, 6, 8]
53+
54+ >>> list(make_points(1, 21, 5))
55+ [6, 11, 16]
56+
57+ >>> list(make_points(1, 5, 2))
58+ [3]
59+
60+ >>> list(make_points(1, 4, 3))
61+ []
62+ """
2963 x = a + h
30- while x < (b - h ):
64+ while x <= (b - h ):
3165 yield x
3266 x = x + h
3367
3468
3569def f (x ): # enter your function here
70+ """
71+ Example:
72+ >>> f(2)
73+ 4
74+ """
3675 y = (x - 0 ) * (x - 0 )
3776 return y
3877
@@ -47,4 +86,7 @@ def main():
4786
4887
4988if __name__ == "__main__" :
89+ import doctest
90+
91+ doctest .testmod ()
5092 main ()
0 commit comments