I would like to know how to make a function with doubles for power without math.h
for example if I want
4.3^2.5
I would like to know how to make a function with doubles for power without math.h
for example if I want
4.3^2.5
Here is a rough outline.
pow(x, y)
is mathematically equivalent to exp(log(x)*y)
except for issues with domains and special cases. log(x)
and exp(x)
can be approximated with series.
Taylor series can be computed from scratch. Advanced implementations use variants of minimax polynomials engineered in advance for specific situations.
Usually, when calculating log
, we separate the exponent part of the argument from the fraction part, then use a polynomial to approximate the logarithm, then add the logarithm for the exponent part.
When calculating exp
, we separate the integer and fraction parts and multiply the exp
of each of them.
With floating-point that uses base two, base-two logarithm and exponentiation are commonly used. Then the logarithm for the exponent e (representing 2e) is simply e.
Since, when doing this, you want to manipulate the exponent and significand parts of floating-point values, you have to access their encodings. math.h
provides routines like frexp
and ldexp
for this. To do it without math.h
, you need to access the bytes of the objects, which is a topic for another Stack Overflow question.
Creating a roughly correct version of pow
is not hard. Calculating the errors and proving bounds on them takes a fair amount of work, and engineering the polynomials and other calculations to reduce the errors is, in general, difficult.