c++ - 求和到几何序列的无穷大

标签 c++ recursion series factorial

问题:

Write C++ function to evaluate the following formula for a given x:

function to be evaluated

以下代码是在 Visual Studio 上用 C++ 设计的,用于解决上述问题。但是,每当我运行代码时,返回的是 x 的值;或我输入的相同值。

我不明白可能是什么问题,所以我将不胜感激。

#include <iostream>
using namespace std;

unsigned long fact(int n) {
    if (n <= 1) {
        return 1;
    }
    else {
        return n * fact(n - 1);
    }
}

unsigned long f(int x, int n) {
    static unsigned long  term;
    static unsigned long sum = 0;
    do {
        term = pow(x, (2 * n + 1)) / fact((2 * n) + 1);
        n++;
        sum += term;
    } while (term < 0.000001);
    return sum;
}

int main() {
    int y = 0;
    int x;
    cout << "enter x" << endl;
    cin >> x;
    cout << f(x, y) << endl;
    system("pause");
}

最佳答案

我建议您不要在每次迭代时都计算幂和阶乘。每个下一个 term 都可以通过将前一个乘以 x^2/[n(n+1)] 来生成:

double sinh_in_disguise(const double x) {
    const double x_sq = x * x;
    double term = x;
    double sum = 0;
    double n = 2;

    while (true) {
        const double new_sum = sum + term;
        if (new_sum == sum)
            break;
        sum = new_sum;
        term *= x_sq / (n * (n + 1));
        n += 2;
    }

    return sum;
}

int main() {
    std::cout.precision(16);
    double x = 2.019;
    std::cout << sinh_in_disguise(x) << std::endl;  // prints 3.699001094869803
    std::cout << std::sinh(x) << std::endl;         // prints 3.699001094869803
}

关于c++ - 求和到几何序列的无穷大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58848942/

相关文章:

c++ - 如何在 C++ 中替换字符串 "ta"中的 "potato"? 2个字符为1

java - 递归查找元素

python - OLS 与 Pandas : datetime index as predictor

c++ - 检测C++ Qt组合中的内存泄漏?

c++ - 如何在 C++ 中添加两个大的 double

c - 数组的整数子集的总和,获取所有结果而不是第一个

javascript - 具有多个系列的 Highchart.js 的正确 json 格式

python - 有没有办法更快地运行此 Python 代码段?

c++ - 是否有满足 C99 标准的 static_assert 替代品?

具有挑战性的递归问题 - 表示进程的树节点