I came across this integral approximation function in a book. It seems efficient and provides accurate results with fewer subintervals ((n)
).
def approximate_integral(a, b, n, f):
delta_x = (b - a) / n
total_sum = 0
for i in range(1, n + 1):
midpoint = 0.5 * (2 * a + delta_x * (2 * i - 1))
total_sum += f(midpoint)
return total_sum * delta_x
Since the above midpoint calculation isn't obvious, I searched for the mathematical formula and implemented it. However, it approaches the correct answer only when I use far more intervals than the implementation found in the book.
midpoint = a + 2 * dx + i * dx
def approximate_integral(a, b, n, f):
dx = (b - a) / n
tot_sum = 0
for i in range(1, n + 1):
midpoint = a + (dx / 2) + (i * dx)
tot_sum += f(midpoint)
return tot_sum * dx
Please explain the efficiency and the differences between this formula and the one I used:
midpoint = 0.5 * (2 * a + delta_x * (2 * i - 1))
I found that the midpoint in my function accounted for an extra interval. After I reduced the ith iteration by 1, it worked as the formula in the book.
midpoint = a + (dx/2) + ((i-1) * dx)