...
Source file
src/math/pow.go
Documentation: math
1
2
3
4
5 package math
6
7 func isOddInt(x float64) bool {
8 xi, xf := Modf(x)
9 return xf == 0 && int64(xi)&1 == 1
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 func Pow(x, y float64) float64
39
40 func pow(x, y float64) float64 {
41 switch {
42 case y == 0 || x == 1:
43 return 1
44 case y == 1:
45 return x
46 case IsNaN(x) || IsNaN(y):
47 return NaN()
48 case x == 0:
49 switch {
50 case y < 0:
51 if isOddInt(y) {
52 return Copysign(Inf(1), x)
53 }
54 return Inf(1)
55 case y > 0:
56 if isOddInt(y) {
57 return x
58 }
59 return 0
60 }
61 case IsInf(y, 0):
62 switch {
63 case x == -1:
64 return 1
65 case (Abs(x) < 1) == IsInf(y, 1):
66 return 0
67 default:
68 return Inf(1)
69 }
70 case IsInf(x, 0):
71 if IsInf(x, -1) {
72 return Pow(1/x, -y)
73 }
74 switch {
75 case y < 0:
76 return 0
77 case y > 0:
78 return Inf(1)
79 }
80 case y == 0.5:
81 return Sqrt(x)
82 case y == -0.5:
83 return 1 / Sqrt(x)
84 }
85
86 absy := y
87 flip := false
88 if absy < 0 {
89 absy = -absy
90 flip = true
91 }
92 yi, yf := Modf(absy)
93 if yf != 0 && x < 0 {
94 return NaN()
95 }
96 if yi >= 1<<63 {
97
98
99 switch {
100 case x == -1:
101 return 1
102 case (Abs(x) < 1) == (y > 0):
103 return 0
104 default:
105 return Inf(1)
106 }
107 }
108
109
110 a1 := 1.0
111 ae := 0
112
113
114 if yf != 0 {
115 if yf > 0.5 {
116 yf--
117 yi++
118 }
119 a1 = Exp(yf * Log(x))
120 }
121
122
123
124
125
126 x1, xe := Frexp(x)
127 for i := int64(yi); i != 0; i >>= 1 {
128 if xe < -1<<12 || 1<<12 < xe {
129
130
131
132
133
134 ae += xe
135 break
136 }
137 if i&1 == 1 {
138 a1 *= x1
139 ae += xe
140 }
141 x1 *= x1
142 xe <<= 1
143 if x1 < .5 {
144 x1 += x1
145 xe--
146 }
147 }
148
149
150
151
152 if flip {
153 a1 = 1 / a1
154 ae = -ae
155 }
156 return Ldexp(a1, ae)
157 }
158
View as plain text