Improved the pow() function to give more exact results

This commit is contained in:
ceriel 1995-12-05 12:29:36 +00:00
parent 812b6f2158
commit 0a643bb9d0

View file

@ -9,46 +9,92 @@
#include <math.h> #include <math.h>
#include <float.h> #include <float.h>
#include <errno.h> #include <errno.h>
#include "localmath.h" #include <limits.h>
double double
pow(double x, double y) pow(double x, double y)
{ {
/* Simple version for now. The Cody and Waite book has double y_intpart, y_fractpart, fp;
a very complicated, much more precise version, but int negexp, negx;
this version has machine-dependent arrays A1 and A2, int ex, newexp;
and I don't know yet how to solve this ??? unsigned long yi;
*/
double dummy;
int result_neg = 0;
if ((x == 0 && y == 0) || if (x == 1.0) return x;
(x < 0 && modf(y, &dummy) != 0)) {
if (x == 0 && y <= 0) {
errno = EDOM; errno = EDOM;
return 0; return 0;
} }
if (x == 0) return x; if (y == 0) return 1.0;
if (y < 0) {
y = -y;
negexp = 1;
}
else negexp = 0;
y_fractpart = modf(y, &y_intpart);
if (y_fractpart != 0) {
if (x < 0) { if (x < 0) {
if (modf(y/2.0, &dummy) != 0) { errno = EDOM;
/* y was odd */ return 0;
result_neg = 1;
} }
}
negx = 0;
if (x < 0) {
x = -x; x = -x;
negx = 1;
} }
if (y_intpart > ULONG_MAX) {
if (negx && modf(y_intpart/2.0, &y_fractpart) == 0) {
negx = 0;
}
x = log(x); x = log(x);
if (x < 0) {
x = -x;
y = -y;
}
/* Beware of overflow in the multiplication */ /* Beware of overflow in the multiplication */
if (x > 1.0 && y > DBL_MAX/x) { if (x > 1.0 && y > DBL_MAX/x) {
errno = ERANGE; errno = ERANGE;
return result_neg ? -HUGE_VAL : HUGE_VAL; return HUGE_VAL;
}
if (negexp) y = -y;
if (negx) return -exp(x*y);
return exp(x * y);
} }
x = exp(x * y); if (y_fractpart != 0) {
return result_neg ? -x : x; fp = exp(y_fractpart * log(x));
}
else fp = 1.0;
yi = y_intpart;
if (! (yi & 1)) negx = 0;
x = frexp(x, &ex);
newexp = 0;
for (;;) {
if (yi & 1) {
fp *= x;
newexp += ex;
}
yi >>= 1;
if (yi == 0) break;
x *= x;
ex <<= 1;
if (x < 0.5) {
x += x;
ex -= 1;
}
}
if (negexp) {
fp = 1.0/fp;
newexp = -newexp;
}
if (negx) {
return -ldexp(fp, newexp);
}
return ldexp(fp, newexp);
} }