Skip to content

Instantly share code, notes, and snippets.

@danielrangelmoreira
Created March 19, 2017 19:37
Show Gist options
  • Save danielrangelmoreira/4304095ecfde8c6027a94544b5db26b0 to your computer and use it in GitHub Desktop.
Save danielrangelmoreira/4304095ecfde8c6027a94544b5db26b0 to your computer and use it in GitHub Desktop.
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
Copy link

Excellent!!!

@soumojit
Copy link

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
Copy link

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