I want to make a exponent function that allows fractions and negatives. I have seen related questions but haven't really found what I'm looking for. I need a function that will be able to do something like this pow(5,1/2)
and pow(7,-2)
. Is there anyone that can help me?
Asked
Active
Viewed 186 times
2

templatetypedef
- 362,284
- 104
- 897
- 1,065

Pocketkid2
- 803
- 1
- 11
- 16
-
1Note that, in C, `1/2` equals 0, so `pow(5, 1/2)` will be `pow(5, 0)`, which is 1. Consider using 1.0f/2 instead – luiscubal Oct 07 '13 at 23:01
-
1for negative powers -- you can just do `1/pow(7,2)` – sukhvir Oct 07 '13 at 23:01
-
1Have you tried [`pow`](http://en.cppreference.com/w/c/numeric/math/pow)? – Oliver Charlesworth Oct 07 '13 at 23:02
-
@OliCharlesworth- I think the question is how to write a function like this from scratch. – templatetypedef Oct 07 '13 at 23:03
2 Answers
1
If you have the ability to compute ex and ln x, then you can use the following identity to compute ab:
ab = eb ln a
It looks like the x86 architecture has native support for computing logarithms; if you look at the x86 instruction listings, the FYL2X
instruction can compute logs. You can probably approximate ex using the Taylor series:
ex = 1 + x + x2 / 2! + x3 / 3! + x4 / 4! + ...
Hope this helps!

templatetypedef
- 362,284
- 104
- 897
- 1,065
-
2Good implementations of math library routines use minimax polynomials or something similar, not Taylor series. Taylor series converge too slowly and have poor error properties. – Eric Postpischil Oct 07 '13 at 23:18
-
@EricPostpischil- Can you post a link to something about that? I'm aware Taylor series aren't the best option, but I haven't heard about minimax polynomials. – templatetypedef Oct 07 '13 at 23:22
-
Start with Wikipedia for background and introduction. There are links in [my answer here](http://stackoverflow.com/a/15351205/298225). I also recommend [Handbook of Floating-Point Arithmetic](http://www.amazon.com/Handbook-Floating-Point-Arithmetic-Jean-Michel-Muller/dp/081764704X). – Eric Postpischil Oct 07 '13 at 23:29
0
if you would like to implement pow
from scratch, then you might want to use Taylor's series.

Zac Wrangler
- 1,445
- 9
- 8
-
Good implementations of math library routines use minimax polynomials or something similar, not Taylor series. Taylor series converge too slowly and have poor error properties. – Eric Postpischil Oct 07 '13 at 23:18