Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

[Problem] composite Simpson’ rule

$
0
0
Hi, thanks for the guys who help me last time
I have been given other task to do which I need help again. the task is this :

Consider Y = F(x) over (a,B)/>/>/>. Suppose that the interval (a,B)/>/>/> is subdivided into 2m subintervals Posted Image of equal width h = (b-a)/2m by using the equally spaced sample points Posted Image,Posted ImagePosted Image. The composite Simpson's rule for 2, subintervals is

Posted ImagePosted ImagePosted Image

Write a program (function) which deliver a numerical approximation of

                     b
(Integrate sign)--->  {  F(x) dx
                     a    


by the composite Simpson’ rule.
Compare the implementation of the composite Simpson’ rule with the rectangle and trapezoidal approximations of a definite integral.

This is what I got so far which I search over the internet to find some code to help to do this task

/* definite integral numerically */

#include <stdio.h>
#include <math.h>
#include "my_lib.h"

#ifndef M_PI 
#define M_PI 3.1415926535897932384626433832795 
#endif

/*this part is the task give me*/
double f(double x)      
{
	return sin(x);
}

/* this part is what I wrote by myself which I'm not really sure is my code right*/
double simp(double a, double b, double f(double), int n)
{
    double h, sum, sum2, t =0;
    int i;
	h = (b-a)/ (2*n);
    for ( i = 1 ; i < n-1; i++)
    {
    sum += f(a + h * i );
    }
    for ( i = 1 ; i <= n ; i++)
    {
    sum2 += f( (a + h) * (2 * i - 1 ));
    }

    t = (h/3) * ( f(a) + f(B)/>/>/>/> + (2 * sum) + (4 * sum2) ) ;
    
    return t;
}

/*this part is the task give me*/
double mid_rect(double a, double b, double f(double), int n) 
{
    double h, sum=0;
    int i;
	h = (b-a)/n;
	for( i = 0 ; i < n ; i++)
		sum += f(a + (i+0.5)*h);
    return sum*h;
}

/*this part is the task give me*/
double trapezoid(double a, double b, double f(double), int n)
{
    double h, sum=0;
    int i;
	h = (b-a)/n;
	for ( i = 0 ; i < n ; i++)
		sum += 0.5*(f(a + i*h) + f(a + i*h + h));
    return sum*h;
}

/*this part is the task give me*/
int main()
{
   int N;
   printf("N = ");
   scanf("%d",&N);

   printf("Simpson' rule Approximation = %f\n", simp(0, 0.5*M_PI, f, N)); /* Wrote by myself */
   printf("Mid Rule Approximation = %f\n", mid_rect(0, 0.5*M_PI, f, N));
   printf("Trapezoid Approximation = %f\n", trapezoid(0, 0.5*M_PI, f, N));
   printf("\n");

   system("pause");
}



thanks for the help

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>