# Numerical Recipes in C: The Art of Scientific Computing, Second Edition

All Stack Overflow 7

Numerical Recipes in C: The Art of Scientific Computing, Second Edition

4.0

Review Date:

I checked this post, but it worked only for whole numbers (1,2,3... not 0.1, 0.3...)

Recursive power function: Why does this work if there's no initial return value?

Then,

I got this from here : Algorithm for pow(float, float)

``````function power(x,n) {
if(n === 0) return 1;
if(n === -1) return 1/x;
if(n === 1) return x;
return Math.exp(n*Math.log(x))
}

console.log(power(2,3.5));
``````

I added some basic checks (n===0)... To fasten things up in case.

Flexo sums it up :

The general algorithm tends to be computing the float power as the combination of the integer power and the remaining root. The integer power is fairly straightforward, the root can be computed using either Newton - Raphson method or Taylor series. IIRC numerical recipes in C has some text on this. There are other (potentially better) methods for doing this too, but this would make a reasonable starting point for what is a surprisingly complex problem to implement. Note also that some implementations use lookup tables and a number of tricks to reduce the computation required.

http://mathworld.wolfram.com/NewtonsMethod.html

http://mathworld.wolfram.com/TaylorSeries.html

http://en.wikipedia.org/wiki/Logarithm#Power_series

https://toptalkedbooks.com/amzn/0521431085

You could start converting this java snippet to C the author states he has converted it from C based on the book numerical recipies which you find online! here