1

Was curious as to why the following produces two different values.

    fmt.Println(51.231576 * math.Pi / 180) // 0.8941596821857065
    fmt.Println(float64(51.231576) * math.Pi / 180) //0.8941596821857064

I understand this is tiny differences but would like to understand why.

Thanks

amwill04
  • 1,330
  • 1
  • 11
  • 18

1 Answers1

3

This has to do with untyped constants. An untyped floating point constant can hold a value with a much higher precission than a typed float64 constant.

So on the second line, in your typed constant expression the multiplication yields a float with a precision much smaller than the multiplication in the untyped constant expression on line one.

Implementation restriction: Although numeric constants have arbitrary precision in the language, a compiler may implement them using an internal representation with limited precision. That said, every implementation must:

  • Represent integer constants with at least 256 bits.
  • Represent floating-point constants, including the parts of a complex constant, with a mantissa of at least 256 bits and a signed binary exponent of at least 16 bits.
  • Give an error if unable to represent an integer constant precisely.
  • Give an error if unable to represent a floating-point or complex constant due to overflow. Round to the nearest representable constant if unable to represent a floating-point or complex constant due to limits on precision.

See related: https://stackoverflow.com/a/57512022/965900

mkopriva
  • 35,176
  • 4
  • 57
  • 71
  • seems crazy that `pointB.Lat * math.Pi / 180 !== pointB.Lat * (math.Pi / 180)` also – amwill04 Oct 15 '19 at 22:50
  • 1
    @amwill04 that's not Go related, that's the imprecision of IEEE-754 64-bit. Here's [go](https://play.golang.com/p/RrMYh53Aq0x) and here's [rust](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d76f8a48492c9394955eeeab85d8da9e). I don't have the links but js and swift return the same thing for me as go and rust. You can try other languages. – mkopriva Oct 15 '19 at 23:15