Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An answer of the exercise: Loops and Functions on a tour of Go
package main
import (
"fmt"
"math"
)
const Delta = 0.0001
func isConverged(d float64) bool {
if d < 0.0 {
d = -d
}
if d < Delta {
return true
}
return false
}
func Sqrt(x float64) float64 {
z := 1.0
tmp := 0.0
for {
tmp = z - (z * z - x) / 2 * z
if d := tmp - z; isConverged(d) {
return tmp
}
z = tmp
}
return z
}
func main() {
attempt := Sqrt(2)
expected := math.Sqrt(2)
fmt.Printf("attempt = %g (expected = %g) error = %g\n",
attempt, expected, attempt - expected)
}
@phedoreanu

This comment has been minimized.

Copy link

@phedoreanu phedoreanu commented Sep 9, 2015

package main

import (
    "fmt"
    "math"
)

func Sqrt(x float64) float64 {
    t, z := 0., 1.
    for {
        z, t = z - (z*z-x)/(2*z), z
        if math.Abs(t-z) < 1e-8 {
            break
        }
    }
    return z
}

func main() {
    i := 169.
    fmt.Println(Sqrt(i))
    fmt.Println(Sqrt(i) == math.Sqrt(i))
}
@real-milos

This comment has been minimized.

Copy link

@real-milos real-milos commented Oct 11, 2015

package main

func Sqrt(x float64) float64 {
    prev, z := float64(0), float64(1)
    for abs(prev - z) > 1e-8 {
        prev = z
        z = z - (z * z - x) / (2 * z)
    }
    return z
}

func abs(number float64) float64 {
    if number < 0 {
        return number * -1
    } else {
        return number
    }
}
@ur0

This comment has been minimized.

Copy link

@ur0 ur0 commented Nov 2, 2015

Here _go_es another one.

package main

import (
  "fmt"
  "math"
)

const Delta = 1e-3

func sqrt(x float64) float64 {
  // x is the input, float64
  // g is the guess, float64
  g := float64(1)
  for {
    // t, what we're looking at
    t := g - (g*g - x)/2 * g
    // d is the delta
    if d := math.Abs(g - t); d < Delta {
      return  t
      break
    }
    g = t
  }
  return g
}

func main() {
  i := 2
  guess := sqrt(2)
  actual := math.Sqrt(2)
  fmt.Printf("Number: %v, Guess: %g, Actual: %g, Delta: %g", i, guess, actual, math.Abs(guess - actual))
}
@cahitbeyaz

This comment has been minimized.

Copy link

@cahitbeyaz cahitbeyaz commented Mar 27, 2017

Solution for 10 iterations:

package main

import ("fmt"
		"math"
		)

func Sqrt(x float64) float64 {
	var zN, zNp1 float64
	zN = 1
	for i:=0;i<10;i++{
		zNp1 = zN - ((zN*zN - x) / (2 * zN))
		zN=zNp1
	}
	return float64(zNp1)
}

func main() {
	nmr:=float64(2)
	guess:=Sqrt(nmr)
	actual:=math.Sqrt(nmr)
	delta:=math.Abs(guess-actual)
	fmt.Println("Number Guess:  Actual   Delta " ,nmr ,guess ,actual,delta)
}
@nickdotht

This comment has been minimized.

Copy link

@nickdotht nickdotht commented Apr 23, 2017

For 10 iterations too:

package main

import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	res := 1.0
	for n := 0; n < 10; n++ {
		res = res - ((res*res - x) / (2 * res))
	}
	return res
}

func main() {
	z := 169.
	fmt.Println(Sqrt(z))
	fmt.Println(math.Sqrt(z))
}
@acesaif

This comment has been minimized.

Copy link

@acesaif acesaif commented May 1, 2017

this is nice algorithm to find sqrt programmatically ... Before I didn't know this ...

package main

import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	z := float64(1)
	for i := 1; i <= 10; i++ {
		z = z - (z*z-x)/(2*z)
	}
	return z
}

func main() {
	p := 6.0
	fmt.Println(Sqrt(p)) // newton's technique  
	fmt.Println(math.Sqrt(p)) // validation by an inbuilt function 
}
@tufank

This comment has been minimized.

Copy link

@tufank tufank commented Jun 15, 2017

package main

import (
	"fmt"
)

const diff = 1e-6

func Sqrt(x float64) float64 {
	z := x
	var oldz = 0.0
	for {
		if v := z - oldz; -diff < v && v < diff {
			return z
		} else {
			oldz = z
			z -= (z*z - x) / (2 * z)
		}
	}
}

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

This comment has been minimized.

Copy link

@donbr donbr commented Nov 21, 2017

I used the statement to calculate 'z' provided in the tutorial. Works very well.

package main

import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	z := x / 2
	for i := 1; i <= 10; i++ {
		z -= (z*z - x) / (2 * z)
		fmt.Printf("Sqrt approximation of %v attempt %v = %v\n", x, i, z)
	}
	return z
}

func main() {
	x := 1525.0
	fmt.Printf("\n*** Newton Sqrt approximation for %v = %v\n", x, Sqrt(x))
	fmt.Printf("*** math.Sqrt response for %v = %v\n", x, math.Sqrt(x))
}
@ceaksan

This comment has been minimized.

Copy link

@ceaksan ceaksan commented Feb 28, 2018

package main

import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	z := float64(1)
	for i := 0; i < 10; i++ {
		z = z - (z * z-x) / (2 * z)
	}
	return z
}

func main() {
	i := float64(169)
	fmt.Println(Sqrt(i), Sqrt(i) == math.Sqrt(i))
}
@danong

This comment has been minimized.

Copy link

@danong danong commented Mar 28, 2018


import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	z := x / 2
	for prev := 0.0; math.Abs(prev-z) > 1e-8; {
		prev = z
		z -= (z*z - x) / (2 * z)
	}
	return z
}

func main() {
	fmt.Println(Sqrt(8))
}
@DersioK

This comment has been minimized.

Copy link

@DersioK DersioK commented Jul 9, 2018

Simplest way to implement the code is as follows:

import "fmt"

func Sqrt(x float64) float64 {
z := float64(1)
for i:=0;i<10;i++{
z -= (zz - x) / (2z)
fmt.Println(z) //Just to view each iteration of z
}
return z
}

func main() {
fmt.Println(Sqrt(2))
}

@justinpage

This comment has been minimized.

Copy link

@justinpage justinpage commented Jul 22, 2018

Here's another take. Instead of fooling around with the delta and absolute values, let's convert the type to something more finite.

package main

import (
	"fmt"
	"math"
)

func Sqrt(start float64) float64 {
	for guess := 1.0; ; {
		state := guess
		guess -= (guess*guess - start) / (2 * guess)

		if float32(state) == float32(guess) {
			return guess
		}
	}
}

func main() {
	fmt.Println(Sqrt(6.0) == math.Sqrt(6.0)) // true
	fmt.Println(Sqrt(2) == math.Sqrt(2))     // true
	fmt.Println(Sqrt(866) == math.Sqrt(866)) // true
}
@TomYeoman

This comment has been minimized.

Copy link

@TomYeoman TomYeoman commented Sep 8, 2019

// SquareRoot x
func SquareRoot(x float64) float64 {
	z, count, thresh := float64(1), 10, float64(0.1)

	for index := 0; index < count; index++ {
		z = z - ((z*z - x) / (2 * z))

		fmt.Printf("Z Val [ %v ] , Predicted [ %v ], Actual [ %v ] \n", z, z*z, x)

		if guess := z * z; math.Abs(guess-x) < thresh {
			fmt.Printf("Fell within threshold of [ %v ] within [ %v ] counts \n", thresh, index)
			break
		}
	}

	return z
}

Sample output

Z Val [ 327 ] , Predicted [ 106929 ], Actual [ 653 ]
Z Val [ 164.49847094801223 ] , Predicted [ 27059.746944234023 ], Actual [ 653 ]
Z Val [ 84.23405635482261 ] , Predicted [ 7095.376249987432 ], Actual [ 653 ]
Z Val [ 45.99313261935662 ] , Predicted [ 2115.3682481417263 ], Actual [ 653 ]
Z Val [ 30.095452195580968 ] , Predicted [ 905.7362428564993 ], Actual [ 653 ]
Z Val [ 25.896541323366037 ] , Predicted [ 670.6308525128048 ], Actual [ 653 ]
Z Val [ 25.556131917093378 ] , Predicted [ 653.1158785638788 ], Actual [ 653 ]
Z Val [ 25.553864778931494 ] , Predicted [ 653.0000051399155 ], Actual [ 653 ]
Fell within threshold of [ 0.1 ] within [ 7 ] counts
@igagankalra

This comment has been minimized.

Copy link

@igagankalra igagankalra commented Jul 4, 2020

package main

import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	z := 1.0
	for x >= z {
		z -= (z*z - x) / (2 * z)
		fmt.Println(z)
		if z == math.Sqrt(x) {
			break
		}

	}
	return z

}

func main() {
	fmt.Println(Sqrt(9999800001))

	fmt.Println("printing")

	fmt.Println(math.Sqrt(9999800001))

}

@horizon365

This comment has been minimized.

Copy link

@horizon365 horizon365 commented Dec 9, 2020


import "fmt"

func Sqrt(x float64) float64{
	z := float64(1)
	mydict := make(map[float64]float64)
	for  {
		z -= (z*z - x) / (x * z)
		_, ok := mydict[z]
		if !ok{
			mydict[z] = z
		} else {
			break
		}
		fmt.Println(z)
	}
	return z
}

func main() {
	fmt.Println(Sqrt(3))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment