使用Simpson规则编写c代码来评估(x ^ 2)(e ^ -x ^ 2)dx的0和y之间的积分(使用固定数量的20,000步)

时间:2017-01-29 00:32:06

标签: c integration integral simpsons-rule

Q的第二部分:然后使用包围和二分法求解y的(x ^ 2)(e ^( - x ^ 2))dx = 0.1的0和y之间的积分。

这是我到目前为止所做的:

    #include <stdio.h>
#include <math.h>
double f(double x, double y);

int main(void) {
    int i, steps;
    double a, b, y, h, m, lower, upper, x, simp, val;
    /*
     * Integrate (x^2)(e^(-x^2)) from 0 to y
     */
    steps = 20000;
    a = 0;
    b = y;
    h= (b-a)/steps;
    /*
     * now apply Simpson's rule. Note that the steps should be even.
     */
    simp = -f(a, y);
    x = a;
    for (i =0; i < steps; i += 2) {
        simp += 2.0*f(x,y)+4.0*f(x+h, y);
        x += 2*h;
    }
    simp += f(b, y);
    simp *= h/3.0;
    /*
     * print out the answer
     */
    printf("The integral from 0 to y with respect to x by Simpson's Rule is %f\n", simp);
    /*
     * Now we need to bracket and bisect to find y
     */
    lower = 0;
    /*
     * Lower bound is from turning point
     */
    upper = 100;
    /*
     *Upper value given.
     */
    while (upper - lower > 10E-10){
        m = (lower + upper)/2;
        val = f(m, y);
        if (val >=0)
            upper = m;
        if (val <=0)
            lower = m;
    }
    m = (lower + upper)/2;
    printf("The value for y is: %lf\n", m);
    return 0; 
}
double f(double x, double y) {
    return pow(x,2)*exp(pow(-x,2))-0.1;
}

Output: The integral from 0 to y with respect to x by Simpson's Rule is -0.000000
The value for y is: 0.302120

它运行但不能完全按照我的需要去做。一旦我使用0和y作为限制,我需要能够继续使用积分。我不能这样做。然后继续并解决y。它给了我一个y值,但是如果我用在线计算器解决的话,它就不一样了。此外,即使我将等式改为积分到x ^ 2,输出也为积分提供零。任何人都可以帮助解释尽可能简单的术语吗?

0 个答案:

没有答案