英文:
Go float number division
问题
我试图在Go中得到2.4/0.8 == 3
w:=float64(2.4)
fmt.Println(math.Floor(w/0.8),math.Floor(2.4/0.8) )
它给我"2 3"。
问题是为什么math.Floor(w/0.8)
不会给我3。是浮点数的精度限制吗?
英文:
I try to get 2.4/0.8 == 3 in Go
w:=float64(2.4)
fmt.Println(math.Floor(w/0.8),math.Floor(2.4/0.8) )
It gives me "2 3".
The question is why math.Floor(w/0.8)
won't give me 3. Is it the precision limit of float number?
答案1
得分: 9
程序的输出是正确的。在IEEE格式中,许多实数的表示并不精确。第一个数字实际上(在其限制为64位的版本中)小于3,所以floor函数正确地返回了'2'。第二个数字在编译时使用更高的精度计算。
推荐阅读:链接。
英文:
The program output is correct. The representation of many real numbers in the IEEE format is not precise. The first number is actually (in the limited 64 bits version of it) less than 3 so floor returns '2' correctly. The second one is computed at compile time using greater precision.
Recomended reading.
答案2
得分: 7
是的,这是精度限制。float64非常精确,但2.4无法在二进制中精确存储。当这两个数字都是常量时,计算在编译时以更高的精度进行,当结果四舍五入为float64时,结果恰好为3。但当其中一个数字是变量时,计算必须在运行时进行,结果为2.9999999999999996,Floor将其截断为2。
英文:
Yes, it is the precision limit. float64 is pretty precise, but 2.4 can't be stored exactly in binary. When both the numbers are constants, the computation is done in higher precision at compile time, and when the result is rounded to float64, it comes out to exactly 3. But when one of the numbers is a variable, the calculation has to be done at runtime, and it comes out to 2.9999999999999996, which Floor truncates to 2.
答案3
得分: -1
尽管这并没有回答问题(为什么),但我在寻找一个四舍五入函数时找到了这个页面,以防万一有人觉得有用,这是我自己的解决方案:
func Round(val float64) (float64) {
if float64(int(val)) < val {
return float64(int(val) + 1)
}
return val
}
英文:
Although this doesn't answer the question(why) I've found this page looking for a round function so just in case someone finds it helpful here is my own solution:
func Round(val float64) (float64) {
if float64(int(val)) < val {
return float64(int(val) + 1)
}
return val
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论