为什么数学.Nextafter(2,3)在Go中增加了0.0000000000000004而不是0.0000000000000001? [英] Why does math.Nextafter(2,3) in Go increment by 0.0000000000000004 instead of 0.0000000000000001?
问题描述
这是从这里采取的: http://tour.golang.org/#5
包主
导入(
fmt
数学
$ b $ func main(){
fmt.Printf(现在你有%g问题。,
math.Nextafter(2,3))
$ / code>
结果:
//现在你有2.0000000000000004个问题。
//程序已退出。
您将拥有与java / scala相同的结果。
math /#Nextafter
函数返回x向y后的下一个可表示值。
Float64frombits(Float64bits(x)+ 1)
正如此主题中所述
A float64 无法表示所有16位数字。
例如,如果x = 0.12345678901234567,使用math.Nextafter
,您可以看到附近的float64值是... 1234565,... 1234566和... 1234568
另见为什么十进制数不能完全用二进制表示?。
或者这个主题:
一些可以用10进制表示的数字在基数2.
例如,数字0.1(基数10)不能完全以基数2表示。
就像0.1(基数3)不能精确表示作为基数10的十进制值:它是0.33333(永远重复)。 golang issue 4398 说明:
const x1 = 1 - float64(1.00000000000000000001)// 0!
规范说明常数值
x
可以转换为类型T
如果x
可以用类型T
的值表示。
1.00000000000000000001
的值不能在float64
中表示。最接近的近似值是1。
This was taken from here: http://tour.golang.org/#5
package main import ( "fmt" "math" ) func main() { fmt.Printf("Now you have %g problems.", math.Nextafter(2, 3)) }
Result:
//Now you have 2.0000000000000004 problems. //Program exited.
解决方案You would have the very same result with java/scala.
Themath/#Nextafter
function "returns the next representable value after x towards y."Float64frombits(Float64bits(x) + 1)
As mentioned in this thread
A float64 cannot express all 16 digit numbers.
For example, if x = 0.12345678901234567, usingmath.Nextafter
, you can see that the nearby float64 values are ...1234565, ...1234566 and ...1234568See also "Why can't decimal numbers be represented exactly in binary?".
Or this thread:Some numbers that are exactly representable in base 10 are not exactly representable in base 2.
For example, the number 0.1 (base 10) can't be exactly represented in base 2.
Just like 0.1 (base 3) can't be exactly represented as a decimal value in base 10: it's 0.33333 (repeats forever).The golang issue 4398 illustrates:
const x1 = 1 - float64(1.00000000000000000001) // 0!
The spec says that a constant value
x
can be converted to typeT
if "x
is representable by a value of typeT
."
The value1.00000000000000000001
is not representable infloat64
; the closest approximation is 1.
这篇关于为什么数学.Nextafter(2,3)在Go中增加了0.0000000000000004而不是0.0000000000000001?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!