tags:

views:

992

answers:

11

Since I was 12, I was always wondering how I can make a function which calculates the power (e.g. 23) myself. In most languages these are included in the standard library, mostly as pow(double x, double y), but how can I write it myself?

I was thinking about for loops, but it think my brain got in a loop (when I wanted to do a power with a non-integer exponent, like 54.5 or negatives 2-21) and I went crazy ;)

So, how can I write a function which calculates the power of a real number? Thanks


Oh, maybe important to note: I cannot use functions which use powers (e.g. exp), which would make this ultimately useless.

+1  A: 

It's an interesting exercise. Here's some suggestions, which you should try in this order:

1) Use a loop. 2) Use recursion (not better, but interesting none the less) 3) Optimize your recursion vastly by using divide-and-conquer techniques 4) Use logarithms

Wouter Lievens
Do you know any algorithms that exist? Thanks
Time Machine
+11  A: 

AB = Log-1(Log(A)*B)

Edit: yes, this definition really does provide something useful. For example, on an x86, it translates almost directly to FYL2X (Y * Log2(X)) and F2XM1 (2x-1):

fyl2x
fld st(0)
frndint
fsubr st(1),st
fxch st(1)
fchs
f2xmi
fld1
faddp st(1),st
fscale
fstp st(1) 

The code ends up a little longer than you might expect, primarily because F2XM1 only works with numbers in the range -1.0..1.0. The fld st(0)/frndint/fsubr st(1),st piece subtracts off the integer part, so we're left with only the fraction. We apply F2XM1 to that, add the 1 back on, then use FSCALE to handle the integer part of the exponentiation.

Jerry Coffin
One problem: `log^-1(x) = exp(x) = e^x`
Time Machine
Very funny recursive definition: the inverse of the logarithm is also a power, I think Koning wants to calculate it with more elemental operations (sum, rest, multiplication, division, etc.)
fortran
Wolfram functions also provides a wide variety of formulae for calculating logarithms. How on earth did this get 3 up votes ! Oh, silly me, it was a joke.
High Performance Mark
+1  A: 

This article provides some solutions for Java. It will be easy to port it in C++.

kgiannakakis
+2  A: 

Wolfram functions gives a wide variety of formulae for calculating powers. Some of them would be very straightforward to implement.

High Performance Mark
+16  A: 

Negative powers are not a problem, they're just the inverse (1/x) of the positive power.

Floating point powers are just a little bit more complicated; as you know a fractional power is equivalent to a root (e.g. x^(1/2) == sqrt(x)) and you also know that multiplying powers with the same base is equivalent to add their exponents.

With all the above, you can:

  • Decompose the exponent in a integer part and a rational part.
  • Calculate the integer power with a loop (you can optimise it decomposing in factors and reusing partial calculations).
  • Calculate the root with any algorithm you like (any iterative approximation like bisection or Newton method could work).
  • Multiply the result.
  • If the exponent was negative, apply the inverse.

Example:

2^(-8.5) = 1 / (2^8 * sqrt(2))
fortran
+2  A: 

For positive integer powers, look at exponentiation by squaring and addition-chain exponentiation.

Richie Cotton
+5  A: 

Typically the implementation of the pow(double, double) function in math libraries is based on the identity:

pow(x,y) = pow(a, y * log_a(x))

Using this identity, you only need to know how to raise a single number a to an arbitrary exponent, and how to take a logarithm base a. You have effectively turned a complicated multi-variable function into a two functions of a single variable, and a multiplication, which is pretty easy to implement. The most commonly chosen values of a are e or 2 -- e because the e^x and log_e(1+x) have some very nice mathematical properties, and 2 because it has some nice properties for implementation in floating-point arithmetic.

The catch of doing it this way is that (if you want to get full accuracy) you need to compute the log_a(x) term (and its product with y) to higher accuracy than the floating-point representation of x and y. For example, if x and y are doubles, and you want to get a high accuracy result, you'll need to come up with some way to store intermediate results (and do arithmetic) in a higher-precision format. The Intel x87 format is a common choice, as are 64-bit integers (though if you really want a top-quality implementation, you'll need to do a couple of 96-bit integer computations, which are a little bit painful in some languages). It's much easier to deal with this if you implement powf(float,float), because then you can just use double for intermediate computations. I would recommend starting with that if you want to use this approach.


The algorithm that I outlined is not the only possible way to compute pow. It is merely the most suitable for delivering a high-speed result that satisfies a fixed a priori accuracy bound. It is less suitable in some other contexts, and is certainly much harder to implement than the repeated-square[root]-ing algorithm that some others have suggested.

If you want to try the repeated square[root] algorithm, begin by writing an unsigned integer power function that uses repeated squaring only. Once you have a good grasp on the algorithm for that reduced case, you will find it fairly straightforward to extend it to handle fractional exponents.

Stephen Canon
+1 here is an example: http://www.netlib.org/fdlibm/e_pow.c
stephan
A: 

A better algorithm to efficiently calculate positive integer powers is repeatedly square the base, while keeping track of the extra remainder multiplicands. Here is a sample solution in Python that should be relatively easy to understand and translate into your preferred language:

def power(base, exponent):
  remaining_multiplicand = 1
  result = base

  while exponent > 1:
    remainder = exponent % 2
    if remainder > 0:
      remaining_multiplicand = remaining_multiplicand * result
    exponent = (exponent - remainder) / 2
    result = result * result

  return result * remaining_multiplicand

To make it handle negative exponents, all you have to do is calculate the positive version and divide 1 by the result, so that should be a simple modification to the above code. Fractional exponents are considerably more difficult, since it means essentially calculating an nth-root of the base, where n = 1/abs(exponent % 1) and multiplying the result by the result of the integer portion power calculation:

power(base, exponent - (exponent % 1))

You can calculate roots to a desired level of accuracy using Newton's method. Check out wikipedia article on the algorithm.

Kent
I meant to mention that the reason that repeated squaring is better is because it is far fewer steps for large powers than a simple iterating loop. If you are familiar with big O notation, the naive solution is O(n), while the repeated squaring approach is O(log(n))
Kent
+3  A: 

Per definition, a^b = exp(b ln(a)) where exp(x) = 1 + x + x^2/2 + x^3/3! + x^4/4! + x^5/5! + ... where n! = 1 * 2 * ... * n.

In practice, you could store an array of the first 10 values of 1/n!, and then approximate exp(x) = 1 + x + x^2/2 + x^3/3! + ... + x^10/10!, because 10! is a huge number, so 1/10! is very small (2.7557319224⋅10^-7).

Andreas Rejbrand
@Pindatjuh: Thanks for trying to make the formatting a bit nicer. But you accidently (I hope) managed to get the formulae entirely wrong. When one writes x^n/n! one always mean (x^n)/(n!), not x^(n/n!).
Andreas Rejbrand
+1  A: 

There are two distinct cases to deal with: Integer exponents and fractional exponents.

For integer exponents, you can use exponentiation by squaring.

def pow(base, exponent):
    if exponent == 0:
        return 1
    elif exponent < 0:
        return 1 / pow(base, -exponent)
    elif exponent % 2 == 0:
        half_pow = pow(base, exponent // 2)
        return half_pow * half_pow
    else:
        return base * pow(base, exponent - 1)

The second "elif" is what distinguishes this from the naïve pow function. It allows the function to make O(log n) recursive calls instead of O(n).

For fractional exponents, you can use the identity a^b = C^(b*log_C(a)). It's convenient to take C=2, so a^b = 2^(b * log2(a)). This reduces the problem to writing functions for 2^x and log2(x).

The reason it's convenient to take C=2 is that floating-point numbers are stored in base-2 floating point. log2(a * 2^b) = log2(a) + b. This makes it easier to write your log2 function: You don't need to have it be accurate for every positive number, just on the interval [1, 2). Similarly, to calculate 2^x, you can multiply 2^(integer part of x) * 2^(fractional part of x). The first part is trivial to store in a floating point number, for the second part, you just need a 2^x function over the interval [0, 1).

The hard part is finding a good approximation of 2^x and log2(x). A simple approach is to use Taylor series.

dan04