go - go1.10之前的Ceiling Func

标签 go

我需要一个自定义的“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/

相关文章:

string - 如何检测何时无法在 Go 中将字节转换为字符串?

git - 无法访问远程存储库以导入 Go 模块

oop - 为什么go语言的方法有奇怪的语法

http - 如何将 io.ReadCloser 流式传输到 http.ResponseWriter

regex - 使用 golangs 正则表达式解析体育比分

在单独的 goroutine 中显示进度的 HTTP 服务器

go - 从 Go 编译器获取 "undefined: distance"错误

Go库包名

Go,OpenAL,DirectSound和Heisenbug

validation - 如何添加开始日期和结束日期的开始验证?