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

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

  1. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    736
    Likes Received:
    39
    Trophy Points:
    28
    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

    Joined:
    Aug 30, 2010
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    china
    oh very good
     
  3. helloword

    helloword New Member

    Joined:
    Aug 30, 2010
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    china
    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

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice