Errors – avec solutions
Copiez votre fonction Sqrt d’un exercice précédent et modifiez-la pour qu’elle renvoie également une valeur d’erreur.
La fonction Sqrt ne supporte pas les nombres complexes et doit donc retourner une valeur d’erreur non nulle lorsqu’on lui donne un nombre négatif.
Créez un nouveau type :
type ErrNegativeSqrt float64
et faites-en une erreur en lui donnant la méthode suivante :
func (e ErrNegativeSqrt) Error() string
de sorte que ErrNegativeSqrt(-2).Error() renvoie "cannot Sqrt negative number : -2".
Note
Un appel à fmt.Sprint(e) à l’intérieur de la méthode Error enverra le programme dans une boucle infinie.
Vous pouvez éviter cela en convertissant d’abord e : fmt.Sprint(float64(e)). Expliquez Pourquoi.
Modifiez votre fonction Sqrt pour qu’elle renvoie une valeur ErrNegativeSqrt lorsqu’on lui donne un nombre négatif.
package main
import (
"fmt"
)
func Sqrt(x float64) (float64, error) {
// TODO: implement
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
Solution
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
res := x
prev := math.NaN()
for {
res = res - (res*res-x)/(2*res)
if math.Abs(res-prev) <= math.SmallestNonzeroFloat64 {
return res, nil
}
prev = res
}
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}