How to work with real numbers in Go?
For instance:
(627.71/640.26)^(1/30) = 0.999340349 --> correct result
but with Go:
fmt.Print(math.Pow((627.71 / 640.26), (1 / 30))) = 1 --> wrong
How to work with real numbers in Go?
For instance:
(627.71/640.26)^(1/30) = 0.999340349 --> correct result
but with Go:
fmt.Print(math.Pow((627.71 / 640.26), (1 / 30))) = 1 --> wrong
Use floating-point (real), not integer, division. For example,
package main
import (
"fmt"
"math"
)
func main() {
fmt.Print(math.Pow((627.71 / 640.26), (1.0 / 30.0)))
}
Playground: https://play.golang.org/p/o7uVw9doaMu
Output:
0.999340348749526
package main
import "fmt"
func main() {
fmt.Println(1 / 30) // integer division
fmt.Println(1.0 / 30.0) // floating-point division
}
Playground: https://play.golang.org/p/VW9vilCC9M8
Output:
0
0.03333333333333333
The Go Programming Language Specification
Integer operators
For two integer values x and y, the integer quotient q = x / y and remainder r = x % y satisfy the following relationships:
x = q*y + r and |r| < |y|
with x / y truncated towards zero ("truncated division").