电源的平方为负指数电源、指数

2023-09-11 02:15:18 作者:空城旧梦

我不知道,如果功率平方需要负指数的照顾。我采取了以下code这适用于只有正数。

I am not sure if power by squaring takes care of negative exponent. I implemented the following code which works for only positive numbers.

    #include <stdio.h>
    int powe(int x, int exp)
    {
         if (x == 0)
            return 1;
         if (x == 1)
            return x;
         if (x&1)
                return powe(x*x, exp/2);
         else
                return x*powe(x*x, (exp-1)/2);       
    }

看着 https://en.wikipedia.org/wiki/Exponentiation_by_squaring 不帮助如下code似乎是错误的。

Looking at https://en.wikipedia.org/wiki/Exponentiation_by_squaring doesn't help as the following code seems wrong.

    Function exp-by-squaring(x, n ) 
      if n < 0  then return exp-by-squaring(1 / x, - n );
      else if n = 0  then return  1;
      else if n = 1  then return  x ; 
      else if n is even  then return exp-by-squaring(x * x,  n / 2);
      else if n is odd  then return x * exp-by-squaring(x * x, (n - 1) / 2).

编辑: 由于阿米特该解决方案同时适用于正数和负数:

Thanks to amit this solution works for both negative and positive numbers:

    float powe(float x, int exp)
    {
            if (exp < 0)
                    return powe(1/x, -exp);
            if (exp == 0)
                    return 1;
            if (exp == 1)
                    return x;
            if (((int)exp)%2==0)
                    return powe(x*x, exp/2);
            else
                    return x*powe(x*x, (exp-1)/2);
    }

对于分指数下面我们可以做(Spektre法):

For fractional exponent we can do below (Spektre method):

假设你有X ^ 0.5,那么您可以轻松地用这种方法计算平方根:从0到x / 2开始,并保持检查X ^ 2等于结果与否的

 
精彩推荐
图片推荐