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))
}
@codehakase

This comment has been minimized.

Copy link

@codehakase codehakase commented Jun 20, 2017

Excellent!!!

@soumojit

This comment has been minimized.

Copy link

@soumojit soumojit commented Jul 19, 2018

package main

import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	z := 1.0
	// First guess
	z -= (z*z - x) / (2*z)
	// Iterate until change is very small
	for zNew, delta := z, z; delta > 0.00000001; z = zNew {
		zNew -= (zNew * zNew - x) / (2 * zNew)
		delta = z - zNew
	}
	return z
}

func main() {
	fmt.Println(Sqrt(2))
	fmt.Println(math.Sqrt(2))
}
@idmcalculus

This comment has been minimized.

Copy link

@idmcalculus 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