Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Finds INTEGRAL of f(x) by Trapezoidal and Simpson method (http://www.go4expert.com/articles/integral-f-x-trapezoidal-simpson-method-t23016/)

coderzone 14Aug2010 19:08

Finds INTEGRAL of f(x) by Trapezoidal and Simpson method
 
Finds INTEGRAL of f(x) by Trapezoidal and Simpson method Simultaneously
Code:

  TRAPEZOIDAL RULE :-
  Integral of F(x) in between the limits a and b is given by
  =(h/2)*(y[0]+2(y[1]+y[2]+y[3]+..y[n-1])+y[n])
  where y[i]=F(x[i]),
  x[i]=x[i-1]+h,
  h=(b-a)/n.

Code:

  SIMPSON RULE :-
  Integral of F(x) in between the limits a and b is given by
  =(h/3)*(y[0]+4(y[1]+y[3]+y[5]+..y[n-1])+2*(y[2]+y[4]+y[6]+..y[n-2])+y[n])
  where y[i],x[i],h as defined above but n needed to be even

The CODE


Code:

#include <stdio.h>
#include <conio.h>
#define N 20
#define n 10
#define F(x) (1/(1+x))
float trap(float,float);
float simp(float,float);
void main()
{
        float a,b,t,s;
        printf("\nEnter the values of a and b\n");
        scanf("%f%f",&a,&b);
        t=trap(a,b);
        s=simp(a,b);
        printf("\nTrapezoidal answer = %g\n",t);
        printf("\nSimpson answer = %g\n",s);
        printf("\nPress any key to exit\n");
        getch();
}
float trap(float a,float b)
{
        float h,x[N],y[N],ans;
        int i;
        h=(b-a)/n;
        y[0]=F(a);
        ans=y[0];
        x[0]=a;
        for(i=1;i<n;i++)
        {
                x[i]=x[i-1]+h;
                y[i]=F(x[i]);
                ans=ans+2*y[i];
        }
        y[n]=F(b);
        ans=ans+y[n];
        ans=ans*h/2;
        return(ans);
}
float simp(float a,float b)
{
        float h,x[N],y[N],ans;
        int i;
        h=(b-a)/n;
        y[0]=F(a);
        ans=y[0];
        x[0]=a;
        for(i=1;i<n;i+=2)
        {
                x[i]=x[i-1]+h;
                y[i]=F(x[i]);
                ans=ans+4*y[i];
        }
        for(i=2;i<n;i+=2)
        {
                x[i]=x[i-1]+h;
                y[i]=F(x[i]);
                ans=ans+2*y[i];
        }
        y[n]=F(b);
        ans=ans+y[n];
        ans=ans*h/3;
        return(ans);
}


helloword 30Aug2010 21:54

Re: Finds INTEGRAL of f(x) by Trapezoidal and Simpson method
 
oh very good

helloword 30Aug2010 21:57

Re: Finds INTEGRAL of f(x) by Trapezoidal and Simpson method
 
hello ,i'm study c++ now, i‘m from china ,my english is not so good ,I hope everyone can learn together

shabbir 4Sep2010 12:21

Re: Finds INTEGRAL of f(x) by Trapezoidal and Simpson method
 
Nominate this article for Article of the month - Aug 2010 before September 15 2010.


All times are GMT +5.5. The time now is 23:52.