定积分辛普森法 1/3
与梯形规则一样,辛普森 1/3 法则也用于找出从范围 a 到 b 的积分值。梯形规则和辛普森 1/3 法则之间的主要区别在于,在梯形规则中,整个部分被分成一些梯形,但在本例中,每个梯形也被分成两部分。
对于此规则,我们将遵循此公式
此处 h 是区间的宽度,n 是区间的数目。我们可以用以下公式找到 h
输入和输出
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
广告