Skip to content

Instantly share code, notes, and snippets.

@tarsisazevedo
Created December 28, 2013 22:42
Show Gist options
  • Save tarsisazevedo/8165159 to your computer and use it in GitHub Desktop.
Save tarsisazevedo/8165159 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt struct {
number float64
}
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("can't square root of negative number: %.f", e.number)
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return x, ErrNegativeSqrt{x}
}
z := 1.0
old_z := 0.0
delta := 0.2
for {
old_z = z
z = z - ((math.Pow(z, 2) - x) / (2 * z))
delta_newton := math.Abs(z - math.Sqrt(x))
if delta_newton <= delta || old_z == z {
return z, nil
}
}
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment