登录
首页 >  Golang >  Go问答

为何在Go语言中浮点数精度不准确

来源:stackoverflow

时间:2024-02-28 14:54:25 421浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《为何在Go语言中浮点数精度不准确》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我使用 %0.1f 将浮点数四舍五入到小数点后 1 位。 然而,我在舍入方面得到了不同的结果。

package main

import "fmt"

func format() {
    name := "granth"
    age := 28
    fmt.print("my name is ", name, " and my age is ", age, "\n")
    fmt.printf("my name is %v and my age is %v\n", name, age)
    fmt.printf("my name is %q and my age is %v\n", name, age)
    fmt.printf("my name is %q and my age is %q\n", name, age)
    fmt.printf("name type is %t and age type is %t\n", name, age)
    fmt.printf("the float is %f\n", 34.55)
    fmt.printf("the float rounded off is %0.1f\n", 35.55)
    fmt.printf("the float rounded off is %0.1f\n", 25.55)
}

输出是:-

my name is Granth and my age is 28
my name is Granth and my age is 28
my name is "Granth" and my age is 28
my name is "Granth" and my age is '\x1c'
name type is string and age type is int
the float is 34.550000
the float rounded off is 35.5
the float rounded off is 25.6

为什么显示 35.55 四舍五入为 35.5,而 25.55 四舍五入为 25.6?

go版本go1.19.1 windows/amd64


正确答案


您的演示文稿均未提供所有有效数字,并且很少有小数真实值可以用二进制浮点数精确表示 在机器级别使用。

因此,如果 35.55 实际上以二进制浮点形式存储为更接近 35.55000000000001 的值,那么当呈现到小数点后一位时,它将变成 35.6,而如果 25.55 更精确地为 25.5499999999999,则它会保留一位小数时四舍五入为 25.5,保留两位小数时四舍五入为 25.55。

为了演示这一点,请将 25.55 显示为更多小数位。我不熟悉 go,它正在处理实数表示,但 IEEE-754 双精度二进制浮点可以将十进制数字表示为大约 15 有效数字的精度。因此,任何不精确的地方都会在 15 个有效数字之后变得明显。

今天关于《为何在Go语言中浮点数精度不准确》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>