Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: Simpson's Rule

Saturday, September 14, 2013

Simpson's Rule




#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<math.h>
double integrand(double x);
FILE *fp;
int main(int argc, char* argv[])
{
double lower_limit,upper_limit,h,*xi,*yi,temp=0.0;
int n,i,invert=0;
if(argc==1)
    {
    printf("\n Enter the number of intervals:");
    scanf("%d",&n);
    printf("\n Enter the lower limit:");
    scanf("%lf",&lower_limit);
    printf("\n Enter the upper limit:");
    scanf("%lf",&upper_limit);
    xi=(double *)malloc((n+1)*sizeof(double));
    yi=(double *)malloc((n+1)*sizeof(double));
    }
else if(argc==2)
    {
    fp=fopen(argv[1],"r");
    fscanf(fp,"%d",&n);
    fscanf(fp,"%lf",&lower_limit);
    fscanf(fp,"%lf",&upper_limit);
    xi=(double *)malloc((n+1)*sizeof(double));
    yi=(double *)malloc((n+1)*sizeof(double));
    }
else
    {
    printf("\n Invalid arguments, program will terminate:");
    exit(1);
    }
if(lower_limit>upper_limit)
    {
    temp=lower_limit;
    lower_limit=upper_limit;
    upper_limit=temp;
    invert=1;
    }
h=(upper_limit-lower_limit)/n;
temp=lower_limit;
for(i=0;i<=n;i++)
    {
    xi[i]=temp;
    temp=temp+h;
    }
printf("  xi\t\t\tyi\n");
temp=0.0;
for(i=0;i<=n;i++)
    {
    yi[i]=integrand(xi[i]);
    printf("%+lf\t\t%+.8lf\n",xi[i],yi[i]);
    if(i==0 || i==n)
        temp+= yi[i];
    else   
        {
        if(i%2==0)
        temp += 2*yi[i];
        else
        temp += 4*yi[i];
        }
    }   
printf("\n Value of the integral using Simpson's Rule is %+.8lf\n",invert==0 ? (h/3.0)*temp:-(h/3.0)*temp);
return 0;
}
double integrand(double x)
    {
    return (log(x));
    }

No comments:

Post a Comment