浮点指数求幂算法

时间:2010-12-13 18:16:56

标签: algorithm math exponentiation

我必须编写一个算法,在整数或浮点参数中取幂基数(整数或浮点数)。我为Deluge(zoho.com)编写了这个算法,但它只能使用整数指数:

float math.potencia(float base, int expoente)
{  
   if(expoente>0)
    {
    base = base * thisapp.math.potencia(base, (input.expoente  -  1));
    }
    else if (expoente == 0)
    {
    base = 1;
    }
    return base;
}

(Deluge没有增强操作符或功能)。谢谢!

2 个答案:

答案 0 :(得分:3)

假设您可以使用sqrt,您可以使用以下算法:

double EPS = 0.0001;

double exponentiation(double base, double exp){
  if(exp >= 1){
    double temp = exponentiation(base, exp / 2);
    return temp * temp;
  } else{
    double low = 0;
    double high = 1.0;

    double sqr = sqrt(base);
    double acc = sqr;    
    double mid = high / 2;

    while(abs(mid - exp) > EPS){
      sqr = sqrt(sqr);

      if (mid <= exp) {
          low = mid;
          acc *= sqr;
      } else{
          high = mid;
          acc *= (1/sqr);
      }

      mid = (low + high) / 2;
    }

    return acc;
  }
}

答案 1 :(得分:1)

好吧,超过17个小时没有回复,最后我找到了自己问题的答案:

以最简单的方式,我们可以使用“e”的值来求解问题,并将数字的对数除以索引:

E 1(日志(数)/指数)

其中number是radicand,index是所需的根。

例如:数字1024的第10个根: e ^(Log(1024)/ 10)= 2。

PS:Log功能的基础也是“e”。 “e”的舍入值为:2.718281828459045

我希望这项技术对你有用。