开发者

Why isn't there Math.Pow that takes an int as the exponent?

I read that the Math.Pow implementation is pretty complicated to be able to handle fractional powers. Why isn't there a version that takes an int for the exponent to make a开发者_运维百科 faster version when you don't need fractional powers?


Because you'd just need to convert it back into a float to multiply it against the logarithm of the base.

nm = em × ln n


For a compiler it is only worthwhile to optimize by converting to a series of multiplies, if the exponent is constant. In which case you can write x*x or x*x*x yourself.

Edit: So if you want to avoid your math is done by the Math.Pow implementation (which uses exponent functions), just don't call it. If Math.Pow would be added for integers, the compiler would have figure out from how it is called if it should emit code for multiplication (if n is constant and small) or the default using exponent functions. That is non-trivial work for a compiler, and there would be no gain in terms of performance.


I don't think that fast math functions was their first priority when they programmed them (see Why is Math.DivRem so inefficient). They could use a expotentiation by square that would be faster, at least for small exponents.

However because floating point is subject to rounding providing 2 different inplementations could mean different results, e.g. for pow(5.9,7) than for pow(5.9,7.0), which may be undesirable in some cases.


Well, you could write your own (in C):

int intPow(int a,int b){
  int answer = a;
  int i;
  for(i=0;i<b-1;i++)
    answer *= a;
  return answer;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜