【C++ 程序】函数积分(使用 std::function)

题目要求

计算积分,例如 ∫ 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 <iostream>
#include <functional>

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;
}

输出示例

a < b

lower bound: -4
upper bound: 2
int_{-4}^{2} (1+x)x dx = 18

XCode Result

a > b

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; };)这就定义了需要的被积函数;
  • 注意需要支持 C++ 11 的编译器,因为这里使用了 std::function(对应头文件 functional);
  • 分析的完善性,lower bound 可能会大于 upper bound。

ALL RIGHTS RESERVED © 2022 Teddy van Jerry
欢迎转载,转载请注明出处。


See also

Teddy van Jerry 的 个人主页
Teddy van Jerry 的 CSDN 导航页
Teddy van Jerry 的 GitHub 主页
Teddy van Jerry 的 博客主页

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值