C语言实现定积分求解方法(一)

2013-09-24 09:20:37 · 作者: · 浏览: 455

  求定积分的方法有很多种,下面是我总结的几种比较常用的方法。

  #include <stdio.h>

  #include <stdlib.h>

  #include <math.h>

  #include <time.h>

  #define N       3

  double fun(double x)

  {

  double y;

  y = sqrt(4-(x)*(x));

  //y = sin(x);

  return y;

  }

  /*随机点法求定积分*/

  double Darts(int n)

  {

  double x, y;

  time_t t;

  int i = 0;

  int count = 0;

  srand((unsigned)time(&t));

  for (i=0; i<n; i++)

  {

  x = rand()%100/100.0;

  y = rand()%100/100.0;

  if (y <= 1-pow(x,2))

  {

  count++;

  }

  }

  return (double)count/(double)n;

  }

  /*左矩形法求定积分*/

  double LeftRect(double down, double up, int n)

  {

  double h, s;

  int i;

  /*计算步长*/

  h = (up-down)/n;

  s = fun(down)*h;

  for (i=1; i<n; i++)

  {

  s = s + fun(down+i*h)*h;

  }

  return s;

  }

  /*梯形公式求定积分*/

  double Trape(double down, double up, int n)

  {

  double h, s;

  int i = 0;

  /*计算步长*/

  h = (up-down)/n;

  s = 0.5*(fun(down)+fun(down+h))*h;

  for (i=1; i<n; i++)

  {

  s = s + 0.5 * (fun(down+i*h) + fun(down+(i+1)*h))*h;

  }

  return s;

  }

  /*复合梯形公式*/

  double T(double x, double y, int z)

  {

  double h, Tn;

  int i = 0;

  h = (y-x)/z;

  Tn = (fun(x)+fun(y))/2;

  for (i=0; i<z; i++)

  {

  Tn = Tn+fun(x+i*h);

  }

  Tn = Tn*h;

  return Tn;

  }