gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:49:45 25 4
gpt4 key购买 nike

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

package main

import (
"fmt"
"math"
)

func main() {
fmt.Printf("Now you have %g problems.",
math.Nextafter(2, 3))
}

结果:

//Now you have 2.0000000000000004 problems.
//Program exited.

最佳答案

你会有 very same result with java/scala
math/#Nextafter 函数“返回 x 之后朝向 y 的下一个可表示值。”

Float64frombits(Float64bits(x) + 1)

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

另见“Why can't decimal numbers be represented exactly in binary?”。
或者这个线程:

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).

golang issue 4398 说明:

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.

关于go - 为什么 Go 中的 math.Nextafter(2,3) 递增 0.0000000000000004 而不是 0.0000000000000001?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25821531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com