پایتون: انتگرالگیری عددی به روش ذوزنقهای
در چند پست آتی قصد دارم که انتگرالگیری عددی به روشهای مختلف را بررسی کنم. برای مطالعه توضیحات مربوط به این روش ها به کتاب کاربرد ریاضیات در مهندسی شیمی (دکتر خراط) مراجعه کنید. در این مطلب به کدنویسی انتگرالگیری عددی به روش ذوزنقهای می پردازیم.
مثال:
# the function to be integrated
def func(x):
return x**2
# define variables
a = 1. # left boundary of area
b = 4. # right boundary of area
dx = 1 # width of the trapezoids
# calculate the number of trapezoids
n = int((b - a) / dx)
# define the variable for area
Area = 0
# loop to calculate the area of each trapezoid and sum.
for i in range(1, n+1):
#the x locations of the left and right side of each trapezpoid
x0 = a+(i-1)*dx
x1 = a+i*dx
#the area of each trapezoid
Ai = dx * (func(x0) + func(x1))/ 2.
# cumulatively sum the areas
Area = Area + Ai
#print out the result.
print ("Area = ", Area)
نتیجه:
Area = 21.5
یک نمونه کد دیگر برای انتگرال گیری عددی به روش ذوزنقه ای:
import numpy as np
x = np.linspace(1, 4, num=4)
y = x**2
I = np.trapz(y, x)
error = (I - 4)/4
print(I, error)
نتیجه:
I = 21.5
error = 4.375