Skip to content

Instantly share code, notes, and snippets.

@siisee11
Last active December 11, 2019 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siisee11/b905465eba41b241861bf7e1dd6a92e9 to your computer and use it in GitHub Desktop.
Save siisee11/b905465eba41b241861bf7e1dd6a92e9 to your computer and use it in GitHub Desktop.
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