You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求不使用pow函数实现ctgⁿx积分的递归与非递归C++方案

实现ctgⁿx原函数的递归与非递归版本(无幂函数依赖)

核心递推关系推导

要避免使用幂函数,需利用三角恒等式转换积分项:

ctgⁿx = ctgⁿ⁻²x · (csc²x - 1) = ctgⁿ⁻²x·csc²x - ctgⁿ⁻²x

结合微分关系 d(ctg x) = -csc²x dx 积分后,得到原函数的递推公式:

F(x, n) = -ctg^(n-1)x/(n-1) - F(x, n-2)

边界条件:

  • 当n=1时,F(x,1) = ln|sinx|
  • 当n=2时,F(x,2) = -ctg x - x

关键说明

ctg^(n-1)x的计算不依赖pow函数或循环实现的幂函数:

  • 递归版本通过递归幂次计算实现(无循环)
  • 非递归版本在递推原函数的过程中,通过逐步乘以ctg(x)*ctg(x)更新幂次(无单独幂次计算循环)

递归版本代码

#include <cmath>

// 递归计算ctg(x)的exponent次幂(无循环)
double cot_power(double cot_x, int exponent) {
    if (exponent == 0) return 1.0;
    if (exponent == 1) return cot_x;
    double half = cot_power(cot_x, exponent / 2);
    return half * cot_power(cot_x, exponent - exponent / 2);
}

// 递归计算原函数F(x,n)
double F_recursive(double x, int n) {
    double cot_x = cot(x);
    
    if (n == 1) {
        return log(fabs(sin(x)));
    }
    if (n == 2) {
        return -cot_x - x;
    }
    
    double cot_pow = cot_power(cot_x, n - 1);
    return -cot_pow / (n - 1) - F_recursive(x, n - 2);
}

非递归版本代码

#include <cmath>

// 非递归计算原函数F(x,n)
double F_iterative(double x, int n) {
    double cot_x = cot(x);
    double result;
    double current_cot_pow;
    int start_n;

    // 初始化边界条件
    if (n % 2 == 1) {
        result = log(fabs(sin(x)));
        start_n = 1;
        current_cot_pow = cot_x * cot_x; // 对应n=3时所需的ctg^2x
    } else {
        result = -cot_x - x;
        start_n = 2;
        current_cot_pow = cot_x * cot_x * cot_x; // 对应n=4时所需的ctg^3x
    }

    // 递推到目标n
    for (int i = start_n + 2; i <= n; i += 2) {
        result = -current_cot_pow / (i - 1) - result;
        current_cot_pow *= cot_x * cot_x; // 更新为下一次递推所需的幂次
    }

    return result;
}

定积分计算示例

基于牛顿-莱布尼茨公式,计算∫(下限b,上限a)ctgⁿx dx:

double calculate_integral(double a, double b, int n) {
    // 注意积分上下限:题目要求下限b,上限a,故结果为F(b,n) - F(a,n)
    return F_iterative(b, n) - F_iterative(a, n);
    // 若使用递归版本,替换为:return F_recursive(b, n) - F_recursive(a, n);
}

注意事项

  • 输入的x不能为kπ(k为整数),否则cot(x)无定义,实际使用时需添加参数校验
  • 原函数中的常数项在定积分中会相互抵消,故实现中省略了常数项

内容的提问来源于stack exchange,提问作者Kaisar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:15:08