1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

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

Discussion in 'C++' started by coderzone, Aug 14, 2010.

  1. coderzone

    coderzone Super Moderator

    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);
    }
    
     
    shabbir likes this.
  2. helloword

    helloword New Member

    oh very good
     
  3. helloword

    helloword New Member

    hello ,i'm study c++ now, i‘m from china ,my english is not so good ,I hope everyone can learn together
     
  4. shabbir

    shabbir Administrator Staff Member

Share This Page