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