计算积分,例如 ∫ a b ( a + x ) x d x \int_a^b(a+x)x\mathrm{d}x ∫ab(a+x)xdx。
/**
* @file main.cpp
* @brief Calculate the sum of a series.
*
* @note C++ 11 is required since we use std::function here.
* @author Teddy van Jerry
* @date 2022-10-27
*/
#include
#include
constexpr double eps = 1E-6; // the integral precision
/**
* @brief Calculate the integral of function f within a range
*
* @param f the function
* @param a the lower bound
* @param b the upper bound
* @return the integral result
*/
double integral(const std::function<double(double)>& f, double a, double b) {
if (a == b) return 0;
else if (a < b) {
double s = 0;
for (double x = a; x < b; x += eps) s += eps * f(x);
return s;
} else return -integral(f, b, a); // reverse the lower and upper bound
}
int main(int argc, const char * argv[]) {
double a, b;
std::cout << "lower bound: ";
std::cin >> a;
std::cout << "upper bound: ";
std::cin >> b;
auto f = [](double x) { return (1 + x) * x; };
std::cout << "int_{" << a << "}^{" << b << "} (1+x)x dx = " << integral(f, a, b) << std::endl;
return 0;
}
lower bound: -4
upper bound: 2
int_{-4}^{2} (1+x)x dx = 18
lower bound: 3
upper bound: -2
int_{3}^{-2} (1+x)x dx = -14.1667
integral
的第一个参数是一个 std::function
类型的。更多关于 std::function
的介绍可以查看 C++ Reference: std::function;main
里,我使用了 lambda 函数(auto f = [](double x) { return (1 + x) * x; };
)这就定义了需要的被积函数;std::function
(对应头文件 functional
);ALL RIGHTS RESERVED © 2022 Teddy van Jerry
欢迎转载,转载请注明出处。
Teddy van Jerry 的 个人主页
Teddy van Jerry 的 CSDN 导航页
Teddy van Jerry 的 GitHub 主页
Teddy van Jerry 的 博客主页