1

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
peterSO
  • 158,998
  • 31
  • 281
  • 276
  • 1
    To trouble-shoot something like this you could look at each part of you calculation and see if it gives you the expected result, quickly you would come to `1 / 30` giving you zero. – Akavall Oct 31 '18 at 04:14
  • 1
    Note that the best approximation to a real number (for whatever reals you like) in Go are mathh/big.Float and the next less accurate are float64s which you used. But _never_ think of them as reals! – Volker Oct 31 '18 at 04:45

1 Answers1

6

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 literals

Floating-point literals

Arithmetic operators

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

peterSO
  • 158,998
  • 31
  • 281
  • 276