Why is pow(int, int) so slow?

pow() works with real floating-point numbers and uses under the hood the formula pow(x,y) = e^(y log(x)) to calculate x^y. The int are converted to double before calling pow. (log is the natural logarithm, e-based) x^2 using pow() is therefore slower than x*x. Edit based on relevant comments Using pow even with integer exponents may … Read more

negative pow in python

(-1.07)1.3 will not be a real number, thus the Math domain error. If you need a complex number, ab must be rewritten into eb ln a, e.g. >>> import cmath >>> cmath.exp(1.3 * cmath.log(-1.07)) (-0.6418264288034731-0.8833982926856789j) If you just want to return NaN, catch that exception. >>> import math >>> def pow_with_nan(x, y): … try: … … Read more

GCC C++ pow accuracy

The function pow operates on two floating-point values, and can raise one to the other. This is done through approximating algorithm, as it is required to be able to handle values from the smallest to the largest. As this is an approximating algorithm, it sometimes gets the value a little bit wrong. In most cases, … Read more

BigInteger.pow(BigInteger)?

You can write your own, using repeated squaring: BigInteger pow(BigInteger base, BigInteger exponent) { BigInteger result = BigInteger.ONE; while (exponent.signum() > 0) { if (exponent.testBit(0)) result = result.multiply(base); base = base.multiply(base); exponent = exponent.shiftRight(1); } return result; } might not work for negative bases or exponents.