Add errors
This commit is contained in:
parent
393cb66cae
commit
df812f2af2
|
@ -0,0 +1,26 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
type ErrNegativeSqrt float64
|
||||
|
||||
func (e ErrNegativeSqrt) Error() string {
|
||||
return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
|
||||
}
|
||||
|
||||
func Sqrt(x float64) (float64, error) {
|
||||
if x < 0 {
|
||||
return 0, ErrNegativeSqrt(x)
|
||||
}
|
||||
z := 1.0
|
||||
for count := 0; count < 10; count++ {
|
||||
z -= (z*z - x) / (2*z)
|
||||
}
|
||||
return z, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println(Sqrt(2))
|
||||
fmt.Println(Sqrt(-2))
|
||||
}
|
Loading…
Reference in New Issue