Daniel Rodríguez
Daniel Rodríguez

Reputation: 774

What is wrong with my implementation for integration using Simpson's Rule

I was creating a C program for solving integrals using the Simpsons rule, I wrote it and it runs, but after giving the program the values it always returns me a value for the definite integral of 0.0000. I rechecked every line at it seems well, here's the code any help to this problem would be appreciated

#include<stdio.h>
#include<math.h>
float ad(int a, int b, int n)
{
    float f4, f2, z, v, q4=0, q2=0, d, m, fa, fb;
    int w=2, g=1, k=1, j=1;
    z=(b-a)/n;
    fa=6*pow(a,2)+16*pow(a,3);
    fb=6*pow(b,2)+16*pow(b,3);
    f4=6*pow(a+z*w,2)+16*pow(a+z*w,3);
    f2=6*pow(a+z*g,2)+16*pow(a+z*g,3);
    v=fa+fb;
    m=v*z;
    while(k<=n/2)
    {

        q4=q4+(z/3)*(4*f4);
        w=w+2; 
        k++;
    }
    while(j<=(n-2)/2)
    {

        q2=q2+(z/3)*(2*f2);
        g=g+2; 
        j++;
    }
    d=m+q4+q2;
    return d;
}
main()
{
    int x, y, l;
    float o;
    printf("Enter number x: ");
    scanf("%d", &x);
    printf("Enter number y: ");
    scanf("%d", &y);
    printf("Enter an even number: ");
    scanf("%d", &l);
    if(l%2!=0)
    {
        printf("The number is odd!\n");
        return 1;

    }
    o=ad(x, y, l);
    printf("The aprox integral is es: %f\n", o);
    return 0;
}    

It also gives me this two errors:

--------------------Configuration: mingw5 - CUI Debug, Builder Type: MinGW--------------------

Checking file dependency...
Compiling E:\anti simpson\ad.cpp...
[Warning] E:\anti simpson\ad.cpp:29: warning: converting to `int' from `float'
[Warning] E:\anti simpson\ad.cpp:50:2: warning: no newline at end of file
Linking...

Complete Make ad: 0 error(s), 2 warning(s)
Generated E:\anti simpson\ad.exe

Upvotes: 0

Views: 253

Answers (2)

Moha the almighty camel
Moha the almighty camel

Reputation: 4443

you declared your function as to return int, but you are returning a float, the result is: the float you are returning gets truncated, and you only get int.

I'm guessing all your integrals had a value between 0 and 1, so the function returned just 0

just change int ad(int a, int b, int n) to float ad(int a, int b, int n)

EDIT: z=(b-a)/n; all a, b and n are ints, you won't get the fractional part in this division. try z=(b-a)/(n * 1.0); just to cast one of the opreands to float so you get the fractional part as well

Upvotes: 3

James Black
James Black

Reputation: 41858

One problem is this line:

int ad(int a, int b, int n)

Change it to:

float ad(int a, int b, int n)

This line and a similar one above it confuses me:

    q2=0;
    q2=q2+(z/3)*(2*f2);

Why set it to zero then set it to a value. I expect it should be set to zero before the while loop.

Upvotes: 3

Related Questions