aboutsummaryrefslogtreecommitdiff
path: root/src/base/math/pow.c
blob: 912a4e1a3b9ba5b1c88517f1e2d6141dffaa6811 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <u.h>
#include <base.h>

double
math·pow(double x, double y) /* return x ^ y (exponentiation) */
{
	double xy, y1, ye;
	long i;
	int ex, ey, flip;

	if(y == 0.0)
		return 1.0;

	flip = 0;
	if(y < 0.){
		y = -y;
		flip = 1;
	}
	y1 = math·modf(y, &ye);
	if(y1 != 0.0){
		if(x <= 0.)
			goto zreturn;
		if(y1 > 0.5) {
			y1 -= 1.;
			ye += 1.;
		}
		xy = math·exp(y1 * math·log(x));
	}else
		xy = 1.0;
	if(ye > 0x7FFFFFFF){	/* should be ~0UL but compiler can't convert double to ulong */
		if(x <= 0.){
 zreturn:
			if(x==0. && !flip)
				return 0.;
			return math·NaN();
		}
		if(flip){
			if(y == .5)
				return 1./math·sqrt(x);
			y = -y;
		}else if(y == .5)
			return math·sqrt(x);
		return math·exp(y * math·log(x));
	}
	x = math·frexp(x, &ex);
	ey = 0;
	i = ye;
	if(i)
		for(;;){
			if(i & 1){
				xy *= x;
				ey += ex;
			}
			i >>= 1;
			if(i == 0)
				break;
			x *= x;
			ex <<= 1;
			if(x < .5){
				x += x;
				ex -= 1;
			}
		}
	if(flip){
		xy = 1. / xy;
		ey = -ey;
	}
	return math·ldexp(xy, ey);
}