有人可以向我解释下面指数函数背后的数学原理吗?

Can someone explain to me the mathematics behind the exponential function below?

我在 https://docs.microsoft.com/en-us/cpp/cpp/constexpr-cpp?view=vs-2019 阅读有关 constexpr 的内容时,看到了如下所示的指数函数的实现。我试图理解其中的逻辑,但无法理解。

我试过 Youtube 和 Google 搜索解释但没有成功。那么,有人可以提供我可以阅读或解释的来源吗?

constexpr float exp(float x, int n)
{
    return n == 0 ? 1 :
        n % 2 == 0 ? exp(x * x, n / 2) :
        exp(x * x, (n - 1) / 2) * x;
};

事情是这样的:我们试图在 y = x ^ n 中找到 y。请注意,exp 在这里是错误的名称 - 它应该是 pow(来自 power)。整个想法基于这个数学方程式:

x ^ n = (x * x) ^ (n / 2) // assuming n is even

n 是奇数时,我们该怎么办?我们从 n 中减去一个,然后将结果乘以 x:

x ^ n = x * (x ^ (n - 1)) // assuming n is odd

因为 n 是奇数,所以 n - 1 是偶数,你使用前面的等式。

编辑: 为此,n 必须是 non-negative,因此 unsigned intn 的更好类型。

显示的过程有时称为 fast exponentiation。您的代码通过递归显示求幂。
这是没有 fast exponentiation 的求幂的想法。让我们计算 x^32。 在非负整数 n 的伪代码中:

long pow( x, n )
    if n == 0 
        return 1 //x^0 = 1
    else
        return x * pow( x, n-1)

以上代码创建了 33 次对函数 pow 的调用:n = 32 时的初始调用到 n = 0 时的最后一次调用。

这里用 fast exponentiation 计算 x^32。

long pow( x, n )
    if n == 0
        return 1
    else if ( n % 2 == 0 ) // n is even 
        return  pow( x * x, n / 2)
        /* Note: x * x = x^2.  When n = 32, we return pow( x^2, 32/2)  or pow(x^2,16).  Also, note that (x^2)^16 = x^32*/
    else 
        return x * pow( x*x, (n - 1)/2 ) 
   /* Here, n is odd, so multiply by x and remove one from n. */

Return 要求快速取幂:

pow( x^2, 32), pow( x^2, 16 ), pow( x^2, 8 ), pow( x^2, 4 ), 
pow( x^2, 2 ), pow( x^2, 1 ), and x * pow( x^2, 0 )

此函数对 pow 进行了 7 次调用,而不是 33 次调用。希望这个解释能解决问题。