This repository has been archived by the owner on Aug 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
int.py
117 lines (86 loc) · 3.87 KB
/
int.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""
Documenation: https://en.wikipedia.org/wiki/Numerical_integration
"""
from typing import Callable
import numpy as np
def trapezoid_integrate(f: Callable[[float], float], a: float, b: float, n: int) -> float:
"""Integrate a function using the trapezoid rule.
Args:
f (Callable[[float], float]): The function to integrate.
a (float): The lower bound of the integral.
b (float): The upper bound of the integral.
n (int): The number of trapezoids to use.
Returns:
float: The integral of the function from a to b.
Raises:
ValueError: The number of trapezoids must be greater than zero.
Doctests:
>>> trapezoid_integrate(lambda x: 1.0, 0.0, 1.0, 100) - 1.0 < 1e-10
True
>>> trapezoid_integrate(lambda x: 1.0, 0.0, 1.0, 1000) - 1.0 < 1e-10
True
>>> trapezoid_integrate(lambda x: 1.0, 0.0, 1.0, 10000) - 1.0 < 1e-10
True
Documenation:
https://en.wikipedia.org/wiki/Trapezoidal_rule
"""
if n <= 0:
raise ValueError("The number of trapezoids must be greater than zero.")
h = (b - a) / n
integral = 0.0
for i in range(n):
integral += (f(a + i * h) + f(a + (i + 1) * h)) * h / 2.0
return integral
def simpson_integrate(f: Callable[[float], float], a: float, b: float, n: int) -> float:
"""Integrate a function using Simpson's rule.
Args:
f (Callable[[float], float]): The function to integrate.
a (float): The lower bound of the integral.
b (float): The upper bound of the integral.
n (int): The number of trapezoids to use.
Returns:
float: The integral of the function from a to b.
Raises:
ValueError: The number of trapezoids must be greater than zero and even.
Doctests:
>>> simpson_integrate(lambda x: 1.0, 0.0, 1.0, 100) - 1.0 < 1e-10
True
>>> simpson_integrate(lambda x: 1.0, 0.0, 1.0, 1000) - 1.0 < 1e-10
True
>>> simpson_integrate(lambda x: 1.0, 0.0, 1.0, 10000) - 1.0 < 1e-10
True
Documenation:
https://en.wikipedia.org/wiki/Simpson%27s_rule
"""
if n <= 0 or n % 2 != 0:
raise ValueError("The number of trapezoids must be greater than zero and even.")
h = (b - a) / n
integral = 0.0
for i in range(n):
integral += (f(a + i * h) + 4.0 * f(a + (i + 0.5) * h) + f(a + (i + 1) * h)) * h / 6.0
return integral
if __name__ == "__main__":
print("Integrating 1/(1+x**2) from -1 to 1:")
for n in [4, 8, 16, 32, 64]:
print(f"n = {n}")
print(
f"trapezoid_integrate(lambda x: 1/(1+x**2), -1.0, 1.0, {n}) = {trapezoid_integrate(lambda x: 1/(1+x**2), -1.0, 1.0, n):.5}" # noqa: E501
)
print(f"Error: {np.abs(np.pi/2 - trapezoid_integrate(lambda x: 1/(1+x**2), -1.0, 1.0, n)):.5}")
print(
f"simpson_integrate(lambda x: 1/(1+x**2), -1.0, 1.0, {n}) = {simpson_integrate(lambda x: 1/(1+x**2), -1.0, 1.0, n):.5}" # noqa: E501
)
print(f"Error: {np.abs(np.pi/2 - simpson_integrate(lambda x: 1/(1+x**2), -1.0, 1.0, n)):.5}")
print()
print("Integrating x**(1/3)*np.exp(np.sin(x)) from 0 to 1:")
for n in [4, 8, 16, 32, 64]:
print(f"n = {n}")
print(
f"trapezoid_integrate(lambda x: x**(1/3)*np.exp(np.sin(x)), 0.0, 1.0, {n}) = {trapezoid_integrate(lambda x: x**(1/3)*np.exp(np.sin(x)), 0.0, 1.0, n):.5}" # noqa: E501
)
print(f"Error: {np.abs(1.29587 - trapezoid_integrate(lambda x: x**(1/3)*np.exp(np.sin(x)), 0.0, 1.0, n)):.5}")
print(
f"simpson_integrate(lambda x: x**(1/3)*np.exp(np.sin(x)), 0.0, 1.0, {n}) = {simpson_integrate(lambda x: x**(1/3)*np.exp(np.sin(x)), 0.0, 1.0, n):.5}" # noqa: E501
)
print(f"Error: {np.abs(1.29587 - simpson_integrate(lambda x: x**(1/3)*np.exp(np.sin(x)), 0.0, 1.0, n)):.5}")
print()