Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Naive way of obtaining square roots with newton's approximation method
package main
import (
"fmt"
//"math"
)
func main() {
const (
x0 = 54777
epsilon = 1.0e-15
)
var (
result = 0.0
xi = 1.0
delta = 1.0
)
for delta >= epsilon {
result = ((xi * xi) + x0) / (2 * xi)
delta = result - xi
xi = result
if delta < 0 {
delta = -delta
}
}
fmt.Println(result)
//fmt.Println(math.Sqrt(x0))
}
@idmcalculus
Copy link

idmcalculus commented Jul 17, 2021

package main

import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	var zi float64 = x/2
	delta := 0.00000001
	z := zi - (zi*zi - x) / (2*zi)
	
	for math.Abs(z-zi) > delta {
		zi = z
		z -= (zi*zi - x) / (2*zi)
		fmt.Printf("%v, %v\n", zi, z)
	}
	return z
}

func main() {
	fmt.Println(Sqrt(0.5))
	fmt.Println("real value = " + fmt.Sprint(math.Sqrt(0.5)))
}

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