1

I'm trying to calculate the integral of sin(x) from 0 to PI in C using a Simpson's Rule function. My program compiles, but I receive the answer of 0.0000 no matter what I input. Can anyone advise?

/*Simpson's Rule*/

#include<stdio.h>
#include<math.h>


/*sin(x) is the function to be integrated*/
double f(double x){
        return sin(x);
}

/*Define the Simpson's Rule function*/
double simps(double f(double x), double a, double b, double n){
        double h, integral, x, sum=0;
        int i;
        h=fabs(b-a)/n;
                for(i=1; i<n; i++){
                        x=a+i*h;
                if(i%2==0){
                        sum=sum+2*f(x);
                }
                else{
                        sum=sum+4*f(x);
                }
        }
        integral=(h/3)*(f(a)+f(b)+sum);
        return integral;
}

/*Main Program*/
main(){
        int n, i;
        double a = 0.0, b = M_PI, h, x, sum=0, integral;
/*Ask for number of intervals */
        printf("\nEnter the number intervals: ");
        scanf("%d",&n);
/*Print the answer */
        printf("\nThe integral of sin(x) using Simpson's Rule is: %lf\n",integral);
        printf("\nActual value of sin(x) from 0 to pi: 2\n");
}

I know the answer should be close to 2, but no matter what I enter for number of intervals I receive the answer of 0.00000.

  • 5
    You don't call the function "simps" at all! – AhmadWabbi Mar 22 '19 at 22:11
  • "It compiles" only says the syntax is correct, not the logic. – stark Mar 22 '19 at 22:18
  • 1
    when I call you function `simps` with n=10, I get `2.000110`. `integral = simps(f, a, b, n);` – MFisherKDX Mar 22 '19 at 22:20
  • Where do I add the ```integral = simps(f, a, b, n)```? – agirlhasnoname Mar 22 '19 at 22:31
  • add it after the `scanf` line – bruceg Mar 22 '19 at 22:36
  • 1
    [`main()` is wrong](https://stackoverflow.com/q/204476/995714) – phuclv Mar 23 '19 at 02:43
  • 2
    When compiling, always enable the warnings, then fix those warnings. ( for `gcc`, at a minimum use: `-Wall -Wextra -Wconversion -pedantic -std=gnu11` ) Note: other compilers use different options to produce the same results. The posted code does NOT compile. The compiler outputs LOTS of warnings, including this serious one: `untitled2.c:38:9: warning: ‘integral’ is used uninitialized in this function [-Wuninitialized]` in this statement in `main()` "printf("\nThe integral of sin(x) using Simpson's Rule is: %lf\n",integral);" – user3629249 Mar 23 '19 at 02:48

0 Answers0