Skip to content

Instantly share code, notes, and snippets.

@marcellodesales
Created April 25, 2012 06:07
Show Gist options
  • Save marcellodesales/2487009 to your computer and use it in GitHub Desktop.
Save marcellodesales/2487009 to your computer and use it in GitHub Desktop.
Sqrt function (Newton's method) using the Google's GO language... Exercise 43...
http://tour.golang.org/#43
As a simple way to play with functions and loops, implement the square root function using Newton's method.
In this case, Newton's method is to approximate Sqrt(x) by picking a starting point z and then repeating:
To begin with, just repeat that calculation 10 times and see how close you get to the answer for various values (1, 2, 3, ...).
The approximation function for the SQRT function returns the given values for the SQRT(4)...
2.5
2.05
2.000609756097561
2.0000000929222947
2.000000000000002
2
2
2
2
2
Next, change the loop condition to stop once the value has stopped changing (or only changes by a very small delta). See if that's more or fewer iterations. How close are you to the math.Sqrt?
Hint: to declare and initialize a floating point value, give it floating point syntax or use a conversion:
z := float64(1)
z := 1.0
package main
import (
"fmt"
)
var p = 0.0
func Sqrt(x float64) float64 {
z := 1.0
for p - z != 0 {
z = newton(z, x)
p = newton(z, x)
}
return z
}
func newton(z, x float64) float64 {
return z - ( ((z*z) - x) / (2*z) )
}
func main() {
fmt.Println(Sqrt(4))
}
@sebest
Copy link

sebest commented May 10, 2014

it does not work with 2, because p - z will never be equal to 0 even if it gets close to it.

@lucashowell
Copy link

Change the import to be:

import (
    "fmt"
    "math"
)

And the for statement to be:

for math.Abs(p - z) > 0.000001 { 

And it will work.

@anjimenezh
Copy link

Bueno mejoran el código inicial:

`package main

import (
"fmt"
"math"
)

func Sqrt(x float64) float64 {
var z, p float64
p = 0
z = 2
for math.Abs(p-z) > 0.000001 {
p = z
z = newton(z, x)
}
return z
}

func newton(z, x float64) float64 {
return z - (((z * z) - x) / (2 * z))
}

func main() {
x:= 90000.0
fmt.Println(Sqrt(x))
fmt.Println(math.Sqrt(x))
}
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment