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

Using c++ to find the limit of a convergent sequence

本文关键字:极限 c++ 查找 使用      更新时间:2023-10-16

我试图获取一个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 = (1/pow(i, 2(+3( 替换为 x = 3 时。然后 if 语句运行并终止程序。我在这里错过了什么吗?如果可以的话,请用虚拟术语告诉我。

这里的问题是你希望一个无限序列会收敛。你应该做的是循环直到它几乎为零,而不是完全为零,例如使用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;
}

这是ideone.com上的代码,但它在处理器时间用完之前不会收敛......

由于double的精度约为 16 位小数,因此需要将 n=100000000 传递给findK表达式才能收敛。当然,您应该从程序中删除std::cout<<x以使其相当快。