MATLAB中的梯形數值積分(不使用trapz函式)
梯形數值積分簡介
梯形數值積分是一種用於求解定積分近似值的方法。它也被稱為梯形法則。在梯形數值積分方法中,我們使用梯形來計算曲線下的面積。
在梯形法則中,我們要積分的總區間被分成較小的子區間。然後,使用梯形近似每個子區間下的曲線面積。之後,透過子梯形面積之和來估計曲線下的總面積。這將是定積分的近似值。
梯形法則公式
以下表達式是梯形數值積分的公式,它給出了定積分的近似值。
$$\mathrm{\int_{a}^{b}f(x)dx\approx \frac{h}{2}[f(a)+2\lbrace{^{n-1}_{i=1}} f(x_{i})+f(b)\rbrace]}$$
其中,
$$\mathrm{x_{i}=a+ih}$$
$$\mathrm{h=\frac{(b-a)}{n}}$$
這裡,“h”是步長或每個子區間的寬度,“n”是子區間的數量,“a”是積分的下限,“b”是積分的上限。
MATLAB中不使用'trapz'函式的梯形數值積分
在MATLAB中,我們可以使用內建函式“trapz”來數值逼近定積分。但是,在本文中,我們將學習不使用“trapz”函式實現梯形數值積分的方法。
為此,讓我們在MATLAB中考慮一些示例程式。
問題(1):使用15個子區間估計曲線$\mathrm{^{2}_{0}(\frac{1}{1+x^{3}})dx}$下的面積。
示例
% MATLAB program demonstrate the trapezoidal numerical integration without using trapz function. % MATLAB program to find area under the curve ∫_0^2 1/(1+x^3) dx using 15 subintervals. % Create a dynamic variable x by using syms function syms x % Specify the lower and upper limits of the integration a = 0; b = 2; % Specify the number of subintervals n = 15; % Define the function to integrate fun1 = 1 / (1+x^3); % Create a function of string containing in fun1 fun = inline(fun1); % h is the step size h = (b - a) / n; % Create a variable S1 that stores the sum of first and last subintervals S1 = fun(a) + fun(b); % Create a variable S that stores the sum of all the subintervals from 1 to (n-1) S = 0; for i = 1:1:n-1 xi = a + (i * h); S = S + fun(xi); end % Apply the formula to perform the numerical integration using Trapezoidal Rule I = (h / 2) * (S1 + 2 * S); % Display the result of the integration disp('Area under the curve 1/(1+x^3) = '); disp(I);
輸出
Area under the curve 1/(1+x^3) = 1.0898
解釋
在這個MATLAB程式中,函式“fun1”指定了我們要積分的函式。變數“a”和“b”分別定義了積分的下限和上限。函式“inline”生成建立了一個包含在函式“fun1”中的字串的函式“fun”。然後,呼叫表示式“h”來計算步長。之後,我們計算第一個和最後一個子區間的和,並將總和儲存在“S1”中。然後,我們指定一個變數“S”來儲存從1到(n-1)的所有子區間的和。之後,我們使用梯形法則公式執行數值積分。最後,我們呼叫“disp”函式來顯示結果。
問題(2):使用10個子區間估計曲線 $\mathrm{^{\pi}_{0}(sin(x))dx}$下的面積。
示例
% MATLAB program demonstrate the trapezoidal numerical integration without using trapz function. % MATLAB program to find area under the curve ∫_0^π sin(x) dx using 10 subintervals. % Create a dynamic variable x by using syms function syms x % Specify the lower and upper limits of the integration a = 0; b = pi; % Specify the number of subintervals n = 10; % Define the function to integrate fun1 = sin(x); % Create a function of string containing in fun1 fun = inline(fun1); % h is the step size h = (b - a) / n; % Create a variable S1 that stores the sum of first and last subintervals S1 = fun(a) + fun(b); % Create a variable S that stores the sum of all the subintervals from 1 to (n-1) S = 0; for i = 1:1:n-1 xi = a + (i * h); S = S + fun(xi); end % Apply the formula to perform the numerical integration using Trapezoidal Rule I = (h / 2) * (S1 + 2 * S); % Display the result of the integration disp('Area under the curve sin (x) = '); disp(I);
輸出
Area under the curve sin (x) = 1.9835
結論
這就是關於在MATLAB中不使用“trapz”函式執行梯形數值積分的所有內容。上述MATLAB示例程式說明了不使用“trapz”函式執行梯形數值積分的簡單實現。