为什么在将float32转换为float64时会失去精度? [英] Why am I losing precision while converting float32 to float64?

查看:141
本文介绍了为什么在将float32转换为float64时会失去精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中丢失了将float32数字转换为float64精度的过程.例如,将359.9转换为float64会生成359.8999938964844.如果float32可以精确存储,为什么float64会丢失精度?

While converting a float32 number to float64 precision is being lost in Go. For example converting 359.9 to float64 produces 359.8999938964844. If float32 can be stored precisely why is float64 losing precision?

示例代码:

package main

import (
    "fmt"
)

func main() {
    var a float32 = 359.9
    fmt.Println(a)
    fmt.Println(float64(a))
}

游乐场

推荐答案

float (即float32)转换为 double时,您从不失去精度(float64).前者必须是后者的子集.

You never lose precision when converting from a float (i.e. float32) to a double (float64). The former must be a subset of the latter.

更多与输出格式化程序的默认精度有关.

It's more to do with the defaulting precision of the output formatter.

最接近359.9的IEEE754 float

The nearest IEEE754 float to 359.9 is

359.899993896484375

最接近359.9的IEEE754 double

The nearest IEEE754 double to 359.9 is

359.8999999999999772626324556767940521240234375

距离359.899993896484375最近的IEEE754 double

The nearest IEEE754 double to 359.899993896484375 is

359.899993896484375

(即是相同的;由于我已经提到过子集规则).

(i.e. is the same; due to the subsetting rule I've already mentioned).

因此您可以看到 float64(a) float64(359.899993896484375)相同,即 359.899993896484375 .这说明了该输出,尽管格式化程序将最后两位数字四舍五入.

So you can see that float64(a) is the same as float64(359.899993896484375) which is 359.899993896484375. This explains that output, although your formatter is rounding off the final 2 digits.

这篇关于为什么在将float32转换为float64时会失去精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆