Skip to content

Instantly share code, notes, and snippets.

@siisee11

siisee11/exercise6.go

Last active Dec 11, 2019
Embed
What would you like to do?
Negative sqrt error
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %f", e)
}
func Sqrt(f float64) (float64, error) {
if f < 0 {
return 0, ErrNegativeSqrt(f)
}
z := 1.0
for {
new_z := z - ((z * z - f) / (2 * f))
if math.Abs(new_z - z) < 1e-10 {
return new_z, nil
}
z = new_z
}
}
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