我需要一个自定义的“Ceil”函数,它像在 go1.10 中一样工作,就像我们在 v1.9 上一样(obv 不会那么高效,但没关系)
例如
天花板(0.33)= 1.00
我已经看到了一些通用的最近整数舍入解决方案,但是,想知道是否有人已经为 v1.9 实现了 equiv 'Ceil' func 作为变通方法?
最佳答案
由于Go是开源的,你可以直接使用他们的代码:https://golang.org/src/math/floor.go?s=720:748#L26
我已经查看了代码并将所有的点点滴滴提取到 this little program 中给你:
package main
import (
"fmt"
"unsafe"
)
func main() {
fmt.Println(ceil(1.5))
fmt.Println(ceil(0.5))
fmt.Println(ceil(0.0))
fmt.Println(ceil(-0.5))
fmt.Println(ceil(-1.5))
}
func ceil(x float64) float64 {
return -floor(-x)
}
func floor(x float64) float64 {
if x == 0 || isNaN(x) || isInf(x, 0) {
return x
}
if x < 0 {
d, fract := modf(-x)
if fract != 0.0 {
d = d + 1
}
return -d
}
d, _ := modf(x)
return d
}
func isNaN(f float64) (is bool) {
return f != f
}
func isInf(f float64, sign int) bool {
return sign >= 0 && f > maxFloat64 || sign <= 0 && f < -maxFloat64
}
func modf(f float64) (int float64, frac float64) {
if f < 1 {
switch {
case f < 0:
int, frac = modf(-f)
return -int, -frac
case f == 0:
return f, f
}
return 0, f
}
x := float64bits(f)
e := uint(x>>shift)&mask - bias
if e < 64-12 {
x &^= 1<<(64-12-e) - 1
}
int = float64frombits(x)
frac = f - int
return
}
const (
maxFloat64 = 1.797693134862315708145274237317043567981e+308
mask = 0x7FF
shift = 64 - 11 - 1
bias = 1023
)
func float64bits(f float64) uint64 {
return *(*uint64)(unsafe.Pointer(&f))
}
func float64frombits(b uint64) float64 {
return *(*float64)(unsafe.Pointer(&b))
}
关于go - go1.10之前的Ceiling Func,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52003064/