使用 c++ 查找收敛序列的极限
Using c++ to find the limit of a convergent sequence
我试图获取一个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
以使其相当快。
相关文章:
- C++向量的极限
- QUdpSocket在高频环境中的极限
- 使用 c++ 查找收敛序列的极限
- 梯度幅度的单位和极限是什么
- 即使在C 中越过初始化阵列的极限后,结果也是如此
- C++17 用于初始化模板类的折叠表达式的极限类型
- OpenMP:即使在深度极限的情况下,递归任务也比顺序慢
- 获得变量极限的优雅方法
- 我能在C/C++中得到堆栈的极限吗
- C++中多重继承的极限
- 阿特金筛子在非常高的极限下出现故障
- 编码以查找 x^2 C++ 的极限
- 检查C++中stoi()函数的int极限
- Barnes Hut和递归极限
- 将巨大的用户输入减少到极限?(C++)
- 如何在没有if-else的情况下无限循环或循环到极限