pzhz9q
Last Updated: February 25, 2016
·
3.438K
· ihcsim
130921 tcl 103 s

Comparing Floating Point Integers In Golang

The Loop and Functions exercise in gotour requires the implementation of the square root function using Newton's method. And one of its challenges is to

stop once the value has stopped changing (or only changes by a very small delta)

A naive approach of using the golang == comparison operator on float64 types will lead to an infinite loop in this exercise.

The way I solve this challenge is by specifying a tolerance, such that two float64 operands are consider equal when the absolute value of their deltas are smaller than the tolerance.

const TOLERANCE = 0.000001
for {
  // Newton's method

  if diff := math.Abs(result - temp); diff < TOLERANCE { // consider equal and break
    break
  } else {
    // do something and continue
  }
}

My full solution to this exercise can be found here. The same repo also contains solutions to other exercises in gotour.

Say Thanks
Respond