Skip to content

Instantly share code, notes, and snippets.

@saaresto
Created October 26, 2018 09:01
Show Gist options
  • Select an option

  • Save saaresto/488946c4b461d3a4a24d5360a62ab9c3 to your computer and use it in GitHub Desktop.

Select an option

Save saaresto/488946c4b461d3a4a24d5360a62ab9c3 to your computer and use it in GitHub Desktop.
Calculate square root using Newton's law (https://tour.golang.org/flowcontrol/8)
package main
import (
"fmt"
"math"
)
const DELTA = 0.000000000000000000000000000001
func sqrt(x float64) (z float64) {
z = x
for tempZ := decrease(z, x); z-tempZ > DELTA; tempZ = decrease(tempZ, x) {
z = tempZ
}
return
}
func decrease(z float64, x float64) float64 {
return z - (z*z-x)/(2*z)
}
func main() {
fmt.Println(sqrt(2))
fmt.Println(math.Sqrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment