summaryrefslogtreecommitdiff
path: root/src/math/pow.c
blob: 6486bc6e5cbad1cc39c25e22f89ecf8456b29727 (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# define TGSOURCE "pow.c"
#include <errno.h>
#include <math.h>
#include "_tgmath.h"

/** exponentiation **/

TYPE TGFN(pow)(TYPE x, TYPE y)
{
	int classx = fpclassify(x);
	int classy = fpclassify(y);

	if (classx == FP_ZERO) {
		if (classy == FP_INFINITE && signbit(y)) {
			feraiseexcept(FE_DIVBYZERO);
			return INFINITY;
		}

		if (y < 0) {
			feraiseexcept(FE_DIVBYZERO);
			/* if (y == odd integer) { */
				return signbit(x) ? - INFINITY : INFINITY;
			/* } else { */
				return INFINITY;
			/* } */
		}

		if (y > 0) {
			/* if (y == odd integer) { */
				return x;
			/* } else { */
				return 0.0;
			/* } */
		}
	}

	if (x == -1.0 && classy == FP_INFINITE) {
		return 1;
	}

	if (x == 1.0) {
		return 1.0;
	}

	if (classy == FP_ZERO) {
		return 1.0;
	}

	if (x < 0 /* && y != integer */) {
		feraiseexcept(FE_INVALID);
		return NAN;
	}

	if (classy == FP_INFINITE) {
		int sb = signbit(y);
		TYPE ab = TGFN(fabs)(x);
		if ((sb && ab < 1.0) || (!sb && ab > 1.0)) {
			return INFINITY;
		} else {
			return 0.0;
		}
	}

	if (classx == FP_INFINITE) {
		if (!signbit(x)) {
			if (y < 0) {
				return 0.0;
			} else if (y > 0) {
				return INFINITY;
			}
		}

		if (y < 0) {
			/* if (y == odd integer ) { */
				return -0.0;
			/* } else { */
				return 0.0;
			/* } */
		}

		if (y > 0) {
			/* if (y == odd integer ) { */
				return - INFINITY;
			/* } else { */
				return INFINITY;
			/* } */
		}
	}

	if (x < 0 /* && !isintegral(y) */) {
		errno = EDOM; /* ARGUMENT(x) is negative and ARGUMENT(y) is not an integer */
		return TGHUGE;
	}

	if (x == 0 && y <= 0) {
		errno = EDOM; /* ARGUMENT(x) is LITERAL(0) and ARGUMENT(y) is less than or equal to LITERAL(0) */
		return TGHUGE;
	}

	if (0) {
		errno = ERANGE; /* The result cannot be represented */
		/* RETURN_FAILURE(CONSTANT(HUGE_VAL), A range error occurred); */
		return TGHUGE;
	}

	/* RETURN_SUCCESS(POW(ARGUMENT(x), ARGUMENT(y))); */
	return x * y;
}

/***
compute ARGUMENT(x) raised to the power ARGUMENT(y).
***/

/*
IMPLEMENTATION(The value returned on a domain error, CONSTANT(HUGE_VAL))
LINK(m)
STDC(1)
*/