ack/lang/cem/libcc.ansi/core/math/pow.c

123 lines
1.5 KiB
C
Raw Normal View History

1989-05-10 16:08:14 +00:00
/*
* (c) copyright 1988 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".
*
* Author: Ceriel J.H. Jacobs
*/
1994-06-24 14:02:31 +00:00
/* $Id$ */
1989-05-10 16:08:14 +00:00
2018-06-21 20:33:47 +00:00
#include <math.h>
#include <float.h>
#include <errno.h>
#include <limits.h>
1989-05-10 16:08:14 +00:00
double
pow(double x, double y)
{
2018-06-21 20:33:47 +00:00
double y_intpart, y_fractpart, fp;
int negexp, negx;
int ex, newexp;
unsigned long yi;
2018-06-21 20:33:47 +00:00
if (x == 1.0)
return x;
2018-06-21 20:33:47 +00:00
if (x == 0 && y <= 0)
{
1989-05-10 16:08:14 +00:00
errno = EDOM;
return 0;
}
2018-06-21 20:33:47 +00:00
if (y == 0)
return 1.0;
1989-05-10 16:08:14 +00:00
2018-06-21 20:33:47 +00:00
if (y < 0)
{
y = -y;
negexp = 1;
}
2018-06-21 20:33:47 +00:00
else
negexp = 0;
y_fractpart = modf(y, &y_intpart);
2018-06-21 20:33:47 +00:00
if (y_fractpart != 0)
{
if (x < 0)
{
errno = EDOM;
return 0;
1989-05-10 16:08:14 +00:00
}
}
1990-08-28 13:59:36 +00:00
negx = 0;
2018-06-21 20:33:47 +00:00
if (x < 0)
{
x = -x;
negx = 1;
}
2018-06-21 20:33:47 +00:00
if (y_intpart > ULONG_MAX)
{
if (negx && modf(y_intpart / 2.0, &y_fractpart) == 0)
{
negx = 0;
}
x = log(x);
/* Beware of overflow in the multiplication */
2018-06-21 20:33:47 +00:00
if (x > 1.0 && y > DBL_MAX / x)
{
errno = ERANGE;
return HUGE_VAL;
}
2018-06-21 20:33:47 +00:00
if (negexp)
y = -y;
2018-06-21 20:33:47 +00:00
if (negx)
return -exp(x * y);
return exp(x * y);
1989-05-10 16:08:14 +00:00
}
2018-06-21 20:33:47 +00:00
if (y_fractpart != 0)
{
fp = exp(y_fractpart * log(x));
}
2018-06-21 20:33:47 +00:00
else
fp = 1.0;
yi = y_intpart;
2018-06-21 20:33:47 +00:00
if (!(yi & 1))
negx = 0;
x = frexp(x, &ex);
newexp = 0;
2018-06-21 20:33:47 +00:00
for (;;)
{
if (yi & 1)
{
fp *= x;
newexp += ex;
}
yi >>= 1;
2018-06-21 20:33:47 +00:00
if (yi == 0)
break;
x *= x;
ex <<= 1;
2018-06-21 20:33:47 +00:00
if (x < 0.5)
{
x += x;
ex -= 1;
}
}
2018-06-21 20:33:47 +00:00
if (negexp)
{
fp = 1.0 / fp;
newexp = -newexp;
}
2018-06-21 20:33:47 +00:00
if (negx)
{
return -ldexp(fp, newexp);
}
return ldexp(fp, newexp);
1989-05-10 16:08:14 +00:00
}