使用中点法进行整合

时间:2014-09-27 01:00:08

标签: c integration polynomials

我需要制作一个C程序,使用中点法来计算三次多项式的积分。

基本上对此进行积分:f(x)= mx ^ 3 + nx ^ 2 + px + q 使用块/中点方法。

到目前为止,我有这个:

#include <stdio.h>
#include <math.h>
int main(){
    char option;
    float m, n, p, q, a, b, N, S=0,T,h;//S for midpoint, T for Trap, h for interval length
    do{
        printf("\n Select one of following options:\n");
        printf("a)Enter new coefficients (m,n,p, and q)\n");
        printf("b)Enter the value for the range from a to b, and N, the number of intervals\n");
        printf("c)Calculate the integral from a to b\n");
        printf("d)Exit\n");

        option=getc(stdin);
        printf("You have selected option: \"%c\" \n", option);

        switch (option){
        case 'a':
            printf("Enter m,n,p,q (in this order):\n");
            scanf("%f%f%f%f", &m,&n,&p,&q);
            break;
        case 'b':
            printf("Enter the interval from a to b and the number of intervals N:");
            scanf("%f%f%f", &a, &b, &N);
            break;
        case 'c':
            h = (b - a) / N;
            for (float i = a; i < b - h; i + h){
                S =+(m*pow(i, 3)) + n*pow(i, 2) + p*i + q;
            }
            S = S*h;
            printf("The integral using midpoint rule: %f", S);
            break;
        case 'd':
            printf("Exit.\n");
            break;
        default:
            printf("Invalid entry, try again... \n");
            break;
        }
    } while (option != 'd');
    return 0;
}

这是我尝试使用的主要算法:

h = (b - a) / N;
            for (float i = a; i < b - h; i + h){
                S =+(m*pow(i, 3)) + n*pow(i, 2) + p*i + q;
            }
            S = S*h;
            printf("The integral using midpoint rule: %f", S);
            break;

但它不起作用。它陷入了循环部分。因为在我输入所有其他变量并选择c选项之后,它就什么也没做。

算法首先找到间隔的长度。然后循环根据中点公式添加函数,这就是我认为我做错了的地方。

2 个答案:

答案 0 :(得分:2)

通常,对循环计数器使用浮点变量被认为是一种不好的做法,因为难以比较浮点值的相等性。解决方法是使用int作为计数器并将其乘以浮点delta:

double delta = (b - a) / N;
double start = a + delta / 2.0;

for (int i = 0; i < N; i++) {
    double x = start + delta * i;

    // do calculations with x
}

答案 1 :(得分:0)

修正了循环:

h = (b - a) / N /2;
            for (float i = a+h; i < b; i=i + 2*h){
                S = S+(m*pow(i, 3)) + n*pow(i, 2) + p*i + q;
            }
            S = S*h*2;

现在完美运作。

相关问题