我有一个场景,在这个场景中,我收到了一个Float64值,但必须将它作为Float32值发送给另一个服务.我们知道接收到的值应该始终适合浮点数32.然而,为了安全起见,我想记录通过转换为Float32而导致数据丢失的情况.

This code block does not compile,因为您不能直接比较Float32和Float64.

func convert(input float64) (output float32, err error) {
    const tolerance = 0.001
    output = float32(input)
    if output > input+tolerance || output < input-tolerance {
        return 0, errors.New("lost too much precision")
    }
    return output, nil
}

Is there an easy way to check that I am hitting this condition?此判断将以高频率进行,因此我希望避免进行字符串转换.

推荐答案

您可以将float32值转换回float64,仅用于验证.

要判断转换后的值是否表示相同的值,只需将其与原始值(输入)进行比较.只返回ok bool个信息(而不是error)也足够/惯用:

func convert(input float64) (output float32, ok bool) {
    output = float32(input)
    ok = float64(output) == input
    return
}

(注意:不会选中像NaN这样的边缘情况.)

测试:

fmt.Println(convert(1))
fmt.Println(convert(1.5))
fmt.Println(convert(0.123456789))
fmt.Println(convert(math.MaxFloat32))

输出(在Go Playground上试用):

1 true
1.5 true
0.12345679 false
3.4028235e+38 true

请注意,这通常会得到ok = false个结果,因为float32的精度低于float64,即使转换后的值可能非常接近输入.

因此,在实践中,判断转换值的差异会更有用.您建议的解决方案判断的绝对差值并不是很有用:例如,1000000.11000000是非常接近的数字,即使差值是0.1.0.00010.00011的差异要小得多:0.00001,但与数字相比,差异要大得多.

因此,您应该判断相对差异,例如:

func convert(input float64) (output float32, ok bool) {
    const maxRelDiff = 1e-8

    output = float32(input)
    diff := math.Abs(float64(output) - input)
    ok = diff <= math.Abs(input)*maxRelDiff

    return
}

测试:

fmt.Println(convert(1))
fmt.Println(convert(1.5))
fmt.Println(convert(1e20))
fmt.Println(convert(math.Pi))
fmt.Println(convert(0.123456789))
fmt.Println(convert(math.MaxFloat32))

输出(在Go Playground上试用):

1 true
1.5 true
1e+20 false
3.1415927 false
0.12345679 false
3.4028235e+38 true

Go相关问答推荐

Go 1.22 net/http群组路由

如何创建两个连接的io.ReadWriteClosers以用于测试目的

SEARCH On Conflict Clause不考虑乐观锁定版本

具有GRPC的RBAC(基于角色的访问控制)-网关生成的REST风格的API

如何将GoFr筛选器用于查询参数?

Golang Gorm Fiber / argon2.Config 未定义

不接受来自 stdin 的重复输入

Go Gin:验证 base64

在 go 中,将接收器 struct 从值更改为指针是否向后兼容?

有没有办法在 Golang 中使用带有 go-simple-mail lib 的代理?

从给定顶点查找图形中所有闭合路径的算法

枚举的 Golang 验证器自定义验证规则

如何模仿联合类型

使用 Golang 在字符串中循环重复数据

Go 泛型:自引用接口约束

github.com/rs/zerolog 字段的延迟判断

关系不存在 GORM

如何在gorm中处理多个查询

如何从 docker-compose 命令运行 2 个不同的命令:

防止在 Go 公用文件夹中列出目录