Why does math.Nextafter(2,3) in Go increment by 0.0000000000000004 instead of 0.0000000000000001?

huangapple go评论76阅读模式
英文:

Why does math.Nextafter(2,3) in Go increment by 0.0000000000000004 instead of 0.0000000000000001?

问题

这是从这里获取的:http://tour.golang.org/#5

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Printf("现在你有%g个问题。",
        math.Nextafter(2, 3))
}

结果:

//现在你有2.0000000000000004个问题。
//程序退出。
英文:

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.

答案1

得分: 8

你可以使用Java/Scala来得到完全相同的结果。math/#Nextafter函数"返回在x和y之间的下一个可表示的值"。

Float64frombits(Float64bits(x) + 1)

此线程所述:

> float64 无法表示所有16位数。例如,如果x = 0.12345678901234567,使用math.Nextafter,你可以看到附近的float64值是...1234565,...1234566和...1234568。

另请参阅"为什么十进制数无法在二进制中精确表示?"。或者这个线程:

> 在十进制中可以精确表示的一些数字在二进制中无法精确表示。例如,数字0.1(十进制)无法在二进制中精确表示。就像0.1(三进制)无法在十进制中精确表示为十进制值一样:它是0.33333(无限循环)。

golang问题4398说明:

const x1 = 1 - float64(1.00000000000000000001) // 0!

> 规范说,如果“x可以由类型T的值表示”,则常量值x可以转换为类型T。值1.00000000000000000001float64中无法表示;最接近的近似值是1。

英文:

You would have the very same result with java/scala.
The math/#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, using math.Nextafter, you can see that the nearby float64 values are ...1234565, ...1234566 and ...1234568

See 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 type T if "x is representable by a value of type T."
The value 1.00000000000000000001 is not representable in float64; the closest approximation is 1.

huangapple
  • 本文由 发表于 2014年9月13日 16:56:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/25821531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定