Has value changed by a very small amount?

Playing with exercise from A Tour of Go

"Next, change the loop condition to stop once the value has stopped changing (or only changes by a very small amount). "

v1 := 1.7320508075688772
v2 := 1.7320508075688774

How do I determine if difference between v1 and v2 is a very small amount?

That depends. By what amount does the value change in which th loop shall continue? How large would you consider an amount to be, that is not very small?

1 Like

Okay, thanks for questions :slight_smile: made it simple:

if v2 - v1 >= 0.0 && v2 - v1 <= 0.00001 {
// …
}

Looks fine to me.

But what if v2 - v1 < 0.0?

A common pattern is to check if math.Abs(v2 - v1) <= epsilon where epsilon is the biggest difference which shall be considered as “only small change”, 0.00001 in your case.

2 Likes

Thank you for the hint. I assumed that v2 must be always greater than v1 in terms of used algorithm.
Anyway, I’ve rewritten code according to your comment:

package main

import (
	"fmt"
	"math"
)

// determination of small change amount
const epsilon = 0.000001

func Sqrt(x float64) float64 {
	z := x / 2
	z2 := z
	var diff float64

	for i := 0; i < 10; i++ {
		z -= (z*z - x) / (2 * z)

		diff = z2 - z
		// instead of math.Abs(diff)
		if diff < 0 {
			diff *= -1
		}

		fmt.Println(i+1, "; z=", z, "; z2 - z=", z2, "-", z, "=", diff)

		if diff <= epsilon {
			break
		}

		z2 = z
	}

	return z
}

func main() {
	x := 3.0
	fmt.Println(Sqrt(x), "Sqrt(", x, ")")
	fmt.Println(math.Sqrt(x), "math.Sqrt(", x, ")")
}