-
Notifications
You must be signed in to change notification settings - Fork 13
/
Power.go
50 lines (44 loc) · 1.23 KB
/
Power.go
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
/**
* @author yang
* @version 0.1 20180722
* Created by yang on 2017/07/22.
************************************************************************************************
* 数值的整数次方:
* 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
* PS:用右移运算替代除以2,用位与0x01运算代替对2取余
************************************************************************************************
*/
package AtOffer
import "errors"
func Power(base float64, exponent int) (float64, error) {
if floatEqual(base, 0.0) && exponent <= 0 {
return 0, errors.New("illegal argument")
}
if exponent < 0 {
return 1.0/powerWithUnsignedExponent(base, -exponent), nil
}
return powerWithUnsignedExponent(base, exponent), nil
}
func powerWithUnsignedExponent(base float64, exponent int) float64 {
if 0 == exponent {
return 1.0
}
if 1 == exponent {
return base
}
result := powerWithUnsignedExponent(base, exponent >> 1)
result = result * result
if 0 != (exponent & 1) {
// exponent是奇数
result *= base
}
return result
}
func floatEqual(a, b float64) bool {
precision := 1e-8
if a > b {
return a - b < precision
} else {
return b -a < precision
}
}