在达到无穷大之前确定最大值
Determining the largest value before hitting infinity
我有一个非常简单的函数,它检查(N^N-1)^(N-2)的值:
int main() {
// Declare Variables
double n;
double answer;
// Function
cout << "Please enter a double number >= 3: ";
cin >> n;
answer = pow(n,(n-1)*(n-2));
cout << "n to the n-1) to the n-2 for doubles is " << answer << endl;
}
根据这个公式,很明显它会达到无穷大,但我很好奇,直到n的多少个数/值达到无穷大?使用循环似乎效率极低,但这就是我所能想到的。基本上,创建一个循环,让n是1-100之间的数字,迭代直到n=inf
有没有更有效的方法来解决这个问题?
我认为你处理这个问题的方式不对。设:F(N)为函数(N^(N-1))(N-2)
现在你实际上知道了可以存储在双类型变量中的最大数字是多少是0x7ff0 0000 0000 0000双精度
所以现在有了F(N)=max_double现在就求解X。这能回答你的问题吗?
两件事:第一件事是(N^(N-1))^(N-2))可以写成N^((N-1。因此,这将删除一个pow
调用,从而使代码更快。
pow(n, (n-1)*(n-2));
第二,要想知道你达到了什么样的实际极限,测试所有N只需要几分之一秒,所以真的没有理由找到另一种实际的方法。
你可以在知道可变大小限制的情况下手动计算它,但测试它肯定更快。代码(C++11,因为我使用std::isinf
)的示例:
#include <iostream>
#include <cmath>
#include <iomanip>
int main() {
double N = 1.0, diff = 10.0;
const unsigned digits = 10;
unsigned counter = digits;
while ( true ) {
double X = std::pow( N, (N-1.0) * (N-2.0) );
if ( std::isinf(X) ) {
--counter;
if ( !counter ) {
std::cout << std::setprecision(digits) << N << "n";
break;
}
N -= diff;
diff /= 10;
}
N += diff;
}
return 0;
}
这个例子在我的计算机上只需要不到一毫秒的时间,并打印17.28894235
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 使用指针从C++中的数组中获取最大值
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 在二维数组中查找最小值和最大值?
- 整数溢出,最大值为 pow(10,19)
- 以C++递归方式查找向量中的最大值
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- C++ 函数,用于查找传入的 N 个数字的平均值、总和、最小值和最大值
- 我的 If Else 语句无法在向量 (C++) 中提供最大值
- 如何使用可变参数模板类使用模板元编程获得最大值
- C++不同的最小最大值实现
- Vec3b:r/g/b 颜色的最大值为 254,而不是 255
- CUDA - 将 float3 数组的 (x,y,z) 分量的最小值/最大值分开?
- 是否可以将无符号 int 的最大值转换为 int 并将结果转换为 -1?
- 查找包含 N 个元素的数组的最小值和最大值
- 井字游戏具有奇怪行为的最小最大值算法(C++)
- 在达到无穷大之前确定最大值
- c++将无穷大转换为最大值,将-inf转换为最小值