dongshan9338 2014-09-13 08:56 采纳率: 0%
浏览 173
已采纳

为什么Go中的math.Nextafter(2,3)会增加0.0000000000000004而不是0.0000000000000001?

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条回答 默认 最新

  • dongzha3058 2014-09-13 09:11
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?