辛普森 1/3 规则用于定积分
辛普森 1/3 规则与梯形规则相似,也用于求解 a 到 b 区间上的积分值。梯形规则和辛普森 1/3 规则的主要区别在于,梯形规则中将整个部分划分为一些梯形,而此方法中每个梯形又分为两部分。
对于此规则,我们将采用以下公式
其中 h是间隔宽度,n 是间隔数量。我们可以使用
输入和输出
Input: The function f(x): (x+(1/x). The lower and upper limit: 1, 2. The number of intervals: 20. Output: The answer is: 2.19315
算法
integrateSimpson(a, b, n)
输入 − 积分的下限和上限以及间隔数量 n。
输出 − 积分后的结果。
Begin h := (b - a)/n res := f(a) + f(b) lim := n/2 for i := 1 to lim, do oddSum := oddSum + f(a + (2i - 1)h) done oddSum := oddSum * 4 for i := 1 to lim-1, do evenSum := evenSum + f(a + 2ih) done evenSum := evenSum * 2 res := res + oddSum + evenSum res := res * (h/3) return res End
示例
#include<iostream> #include<cmath> using namespace std; float mathFunc(float x) { return (x+(1/x)); //function 1 + 1/x } float integrate(float a, float b, int n) { float h, res = 0.0, oddSum = 0.0, evenSum = 0.0, lim; int i; h = (b-a)/n; //calculate the distance between two interval res = (mathFunc(a)+mathFunc(b)); //initial sum using f(a) and f(b) lim = n/2; for(i = 1; i<=lim; i++) oddSum += mathFunc(a+(2*i-1)*h); //sum of numbers, placed at odd number oddSum *= 4; //odd sum are multiplied by 4 for(i = 1; i<lim; i++) evenSum += mathFunc(a+(2*i)*h); //sum of numbers, placed at even number evenSum *= 2; //even sum are multiplied by 2 res += oddSum+evenSum; res *= (h/3); return res; //The result of integration } main() { float result, lowLim, upLim; int interval; cout << "Enter Lower Limit, Upper Limit and interval: "; cin >>lowLim >>upLim >>interval; result = integrate(lowLim, upLim, interval); cout << "The answer is: " << result; }
输出
Enter Lower Limit, Upper Limit and interval: 1 2 20 The answer is: 2.19315
广告