在达到无穷大之前确定最大值

Determining the largest value before hitting infinity

本文关键字:最大值 无穷大      更新时间:2023-10-16

我有一个非常简单的函数,它检查(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