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.
geoyws
  • 2,457
  • 26
  • 36
  • 2
    I guess because `2.0000000000000001` can't be represented as a 64 bit floating point number. https://golang.org/src/pkg/math/nextafter.go – david Sep 13 '14 at 09:04

1 Answers1

8

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.

Community
  • 1
  • 1
VonC
  • 1,042,979
  • 435
  • 3,649
  • 4,283