Last active
December 11, 2019 11:12
-
-
Save siisee11/b905465eba41b241861bf7e1dd6a92e9 to your computer and use it in GitHub Desktop.
Negative sqrt error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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