计算积分

Calculating Integrals

我正在尝试用 C++ 计算积分,我正在尝试使用 Simpson's 3/8 Rule(也称为辛普森第二定律)来计算它。我写了一个程序,但它给出了错误的结果。当我在纸上使用相同的规则时,它起作用了。不知道怎么回事
simpsons.cpp :

#include <iostream>

double f(int x) {
  return 3*(x*x)+2*x+5;
}

float integralf(int lower_end, int high_end) {
  int a = lower_end;
  int b = high_end;
  double area = 0.0;
  area = ((b - a)/8)*(f(a) + 3*f((2*a+b)/3) + 3*f((a+2*b)/3) + f(b));
  return area;
}

int main() {
  int lower = -3;
  int high = 5;
  std::cout << integralf(lower, high) << std::endl;

  return 0;
}

它给出了 194,但答案是 208。我尝试了与 Reimann 求和技术相同的积分,它给出了 166.24。
reimann.cpp :

#include <iostream>

double f(int x) {
  return 3*(x*x)+2*x+5;
}

double integral(double low_end, double high_end, double steps) {
  double step = (high_end - low_end)/steps;
  double area = 0.0;
  double y = 0;
  double x = 0;

  for(int i=0;i<=steps;++i) {
    x = low_end + i * step;
    y = f(x);
    area += y * step;
  }

  return area;
}

int main() {
  int low_end = -3;
  int high_end = 5;
  int steps = 100;
  std::cout << integral(low_end, high_end, steps) << std::endl;

  return 0;
}

不知道怎么回事。有没有更好的方法来计算cpp中的积分?欢迎大家提出建议。

解决方案

编辑:我做到了。代码的最终版本 (simpsons.cpp) :

#include <iostream>

double f(double x) {
  return 3*(x*x)+2*x+5;
}

float integralf(double lower_end, double high_end) {
  double a = lower_end;
  double b = high_end;
  double h = (b - a)/3;
  double area = 0.0;
  area = ((3*h)/8)*(f(a) + 3*f((2*a+b)/3) + 3*f((a+2*b)/3) + f(b));
  return area;
}

int main() {
  int lower = -3;
  int high = 5;
  std::cout << integralf(lower, high) << std::endl;

  return 0;
}

给出的答案是208

代码的最终版本(simpsons.cpp):

#include <iostream>

double f(double x) {
  return 3*(x*x)+2*x+5;
}

float integralf(double lower_end, double high_end) {
  double a = lower_end;
  double b = high_end;
  double h = (b - a)/3;
  double area = 0.0;
  area = ((3*h)/8)*(f(a) + 3*f((2*a+b)/3) + 3*f((a+2*b)/3) + f(b));
  return area;
}

int main() {
  int lower = -3;
  int high = 5;
  std::cout << integralf(lower, high) << std::endl;

  return 0;
}

给出的答案是208