To Compute the Value of Integration Using Trapezoidal Method of Numerical Integration - C Data Structure

C examples for Data Structure:Algorithm

Description

To Compute the Value of Integration Using Trapezoidal Method of Numerical Integration

Demo Code

#include<stdio.h>
#define MAX 50//ww w  . j  av  a 2 s  .c o m

float trapezoid(float x)
{
    return (1/(1+x*x));
}

int main()
{
  int i, num;
  float a, b, h, x[MAX], y[MAX], sumOdd, sumEven, result;

  a = 2;
  b = 5;
  h = 20;
  num = (b - a) / h;
  if(num%2 == 1)
    num = num + 1;
  h = (b - a) / num;
  printf("Refined value of h, the width of trapezium : %5.3f", h);
  printf("\nRefined value of num, the number of trapaziums : %d\n", num);
  for(i=0; i <= num; i++) {
    x[i] = a + i * h;
    y[i] = trapezoid(x[i]);
  }
  sumOdd = 0;
  sumEven = 0;
  for(i=1; i < num; i++) {
    if(i%2 == 1)
      sumOdd = sumOdd + y[i];
    else
      sumEven = sumEven + y[i];
  }
  result = h / 3 * (y[0] + y[num] + 4 * sumOdd + 2 * sumEven);
  printf("\nValue of Integration : %5.3f", result);
}

Result


Related Tutorials