Skip to content

Commit 235becf

Browse files
authored
Create romberg_integration.py
1 parent b0c243c commit 235becf

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

romberg_integration.py

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
def function(x):
2+
return x*3 + x*2 + x + 1
3+
4+
def trapezoidal(function, a, b, n):
5+
h = (b - a) / n
6+
integration = function(a) + function(b)
7+
8+
for i in range(1, n):
9+
k = a + i * h
10+
integration += 2 * function(k)
11+
12+
integration *= h / 2
13+
return integration
14+
15+
def simp_one_third(function, a, b, n):
16+
h = (b - a) / n
17+
integration = function(a) + function(b)
18+
19+
for interval in range(1, n):
20+
x = a + interval * h
21+
if interval % 2 == 0:
22+
integration += 2 * function(x)
23+
else:
24+
integration += 4 * function(x)
25+
26+
integration *= h / 3
27+
return integration
28+
29+
def simp_third_eight(function, a, b, n):
30+
h = (b - a) / n
31+
integration = function(a) + 3 * function(a + h) + 3 * function(a + 2 * h) + function(b)
32+
33+
for i in range(3, n, 2):
34+
integration += 4 * function(a + i * h)
35+
36+
for i in range(4, n, 2):
37+
integration += 2 * function(a + i * h)
38+
39+
integration *= 3 * h / 8
40+
return integration
41+
42+
def romberg_integration(method, function, a, b, n):
43+
table = []
44+
for i in range(n + 1):
45+
row = [0] * (n + 1)
46+
table.append(row)
47+
for i in range(0, n+1):
48+
if method == "trapezoidal":
49+
table[i][0] = trapezoidal(function, a, b, 2**i)
50+
elif method == "simpson_one_third":
51+
table[i][0] = simp_one_third(function, a, b, 2**i)
52+
elif method == "simpson_three_eight":
53+
table[i][0] = simp_third_eight(function, a, b, 3*2**i)
54+
55+
for j in range(1, n+1):
56+
for i in range(j, n+1):
57+
table[i][j] = (4*j * table[i][j-1] - table[i-1][j-1]) / (4*j - 1)
58+
59+
return table[n][n]
60+
61+
62+
lower_limit = float(input("Enter lower limit: "))
63+
upper_limit = float(input("Enter upper limit: "))
64+
num_intervals = int(input("Enter number of intervals: "))
65+
66+
print("Choose the method to solve Romberg integration:")
67+
print("1. Trapezoidal")
68+
print("2. Simpson's 1/3")
69+
print("3. Simpson's 3/8")
70+
71+
method_choice = int(input("Enter method choice (1, 2, or 3): "))
72+
73+
if method_choice == 1:
74+
method = "trapezoidal"
75+
elif method_choice == 2:
76+
method = "simpson_one_third"
77+
elif method_choice == 3:
78+
method = "simpson_three_eight"
79+
else:
80+
print("Invalid method choice. Please choose a valid method.")
81+
82+
83+
result = romberg_integration(method, function, lower_limit, upper_limit, num_intervals)
84+
print("Integration result using Romberg with %s method: %0.4f" % (method, result))

0 commit comments

Comments
 (0)