Calculate fractional exponent in for loop without power function
My maths in this area is a bit shaky. Does anybody know how I can calculate a power such as 10^2.2 using no maths functions other than */-+ and a for loop? I don't have access to a maths library (and can't i开发者_如何转开发mport/include it), but need to calculate these things. Hmm.. maybe I should just look how the math library does it.
You can compute logs & exponentials using only basic arithmetic with a Taylor (or Maclaurin) series expansion. So, you should be able to take advantage of certain identities:
exp(ln(a)) = a
ln(a^b) = b*ln(a)
ln(1+x) = x - (x^2)/2 + (x^3)/3 - ... + ...
exp(x) = 1 + x + (x^2)/2 + ...
See what you can make of all of this...
Given that:
a ^ (m / n) == nth_root(a) ^ m
Convert your exponent to a fraction, then compute the nth root, and then raise the result to the mth power.
(You'll have to write your own pow
function.)
You can use this method - http://mathworld.wolfram.com/ContinuedFraction.html to get a very close approximation.
Express the exponent as fraction and separate both parts (if the numbers get too big, you can use continued fraction expansion to get a good approximation):
2.2 = 22/10 = 11/5
10^2.2 = 10^(11/5) = (10^11)^(1/5)
The integer parts shouldn't be a problem (see http://en.wikipedia.org/wiki/Exponentiation_by_squaring). Then you can calculate the root by one of the algorithms described here: http://en.wikipedia.org/wiki/Nth_root_algorithm
精彩评论