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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算