Skip to content

Instantly share code, notes, and snippets.

@konabe
Created May 21, 2019 08:50
Show Gist options
  • Save konabe/cceee83de8662c69971fd0643b14ca18 to your computer and use it in GitHub Desktop.
Save konabe/cceee83de8662c69971fd0643b14ca18 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %f", e)
}
func Sqrt(x float64) (float64, error) {
if x < 0{
return 0, ErrNegativeSqrt(x)
}
z := 1.0
z_pre := 0.0
i := 1
for math.Abs(z - z_pre) > 1e-10 {
z_pre = z
z -= (z*z - x) / (2*z)
i++
}
return z, nil
}
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