Friday, May 8, 2020

Math lesson in A Tour of Go

Revisiting the "Tour of Go" language after many years because I have some time in my hand... and it contains a delightful math lesson. Implementing the square root. It is Newton's Method in action!

Let's see if you can crack this: https://tour.golang.org/flowcontrol/8

Ok don't like Go? use your favorite language. But I feel empowered to able to do my own square root method and not rely on Math.sqrt().

Go's syntax is somewhat between C and Pascal so far... and has pointers.

My answer:

package main

import (
 "fmt"
 "math"
)

func Sqrt(x float64) float64 {
 z := 1.0
 e := 0.0001

 for math.Abs(z*z-x) > e {
  z -= (z*z - x) / (2 * z)

  //fmt.Println(z)
 }
 return z
}

func main() {
 fmt.Println(Sqrt(2))
}
Note: in Go, "while" loop is spelled "for". There is only ONE kind of loop. And many modern new languages like to do the types behind, like Pascal. My Tour of Go didn't go very far. But Go's power is in its concurrency ability... the go routines and "chan" or channels, which isn't exactly easy to master.