使用c ++查找收敛序列的极限

问题描述 投票:0回答:2

我正在尝试获得一个if语句,以在满足收敛序列的限制时终止程序,在这种情况下,为3+(1 / k ^ 2)= 3。

#include <iostream>
#include <math.h>

int findK(int k)
{
        double x = 0;
        for(double i=2;i<k;i++)
        {
                x = (1/pow(i, 2)+3);
                if(std::fmod(x, 1.0) == 0)
                {
                        std::cout << "Sequence terminated at, " << i << "th term.\n";               
                        exit(0);
                }
                else
                {
                        std::cout << x;
                }
                if(i != k-1) std::cout << ", ";
        }
        std::cout << std::endl;
}

int main()
{
        int n = 453;
        findK(n);

        return 0;
}

我不是最擅长数学或编程/ c ++的人,但是在我看来,一旦序列达到3,if语句就不会触发。当我用x = 3替换x =(1 / pow(i,2)+3)时,if语句将运行并终止程序。我在这里想念什么吗?如果可以的话,请用虚假的方式告诉我。

c++ sequence limit infinite convergence
2个回答
0
投票

这里的问题是,您希望无限序列会收敛。您应该做的就是循环直到它几乎为零,而不是精确地为零,例如使用std::numeric_limits<double>::epsilon(),向我们提供此代码-我每次循环时都在std::numeric_limits<double>::epsilon()结果中添加了打印,以便您看到正在发生的情况:

std::fmod()

这是#include <iostream> #include <cmath> #include <limits> int findK(int k) { double x = 0; for(double i=2;i<k;i++) { x = (1/pow(i, 2)+3); if(std::fmod(x, 1.0) <= std::numeric_limits<double>::epsilon()) { std::cout << "Sequence terminated at, " << i << "th term.\n"; exit(0); } else { std::cout << x << "; " << std::fmod(x, 1.0) << ", "; } if(i != k-1) std::cout << ", "; } std::cout << std::endl; } int main() { int n = 453; findK(n); return 0; } ,但是在用尽处理器时间之前不会收敛...


0
投票

因为the code on ideone.com的精度约为16位小数,所以需要将n = 100000000传递给ideone.com以便使表达式收敛。当然,您应该从程序中删除double以使其变得相当快。


0
投票

因为the code on ideone.com的精度约为16位小数,所以需要将n = 100000000传递给ideone.com才能使表达式收敛。当然,您应该从程序中删除double以使其变得相当快。

© www.soinside.com 2019 - 2024. All rights reserved.