Skip to content

Instantly share code, notes, and snippets.

@royling
Last active December 16, 2015 00:59
Show Gist options
  • Save royling/efea153cb2d8706219d1 to your computer and use it in GitHub Desktop.
Save royling/efea153cb2d8706219d1 to your computer and use it in GitHub Desktop.
go-tour exercise1: implement the square root function using Newton's method
package main
import (
"fmt"
"math"
)
const Delta = float64(1e-15)
func Sqrt(x float64) float64 {
z := float64(1)
for {
d := (z*z - x)/z/2
if math.Abs(d) < Delta {
break
} else {
z -= d
//fmt.Println(z)
}
}
return z
}
func main() {
fmt.Println(Sqrt(4))
fmt.Println(math.Sqrt(3))
}
package main
import (
"fmt"
"math"
)
const Delta = float64(1e-15)
func Sqrt(x float64) (z float64) {
z = float64(1)
for {
d := (z*z - x)/z/2
if math.Abs(d) < Delta {
break
} else {
z -= d
}
}
return
}
func main() {
fmt.Println(Sqrt(3))
fmt.Println(math.Sqrt(3))
}
package main
import (
"fmt"
"math"
)
const Delta = float64(1e-15)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
// here needs to convert e (float64(e)) first;
// otherwise, it will go to an infinite loop, causing out of memory
return fmt.Sprint("cannot Sqrt negative number:", float64(e))
}
func Sqrt(x float64) (float64, error) {
var (
err error
z float64
)
if x < 0 {
err = ErrNegativeSqrt(x)
} else {
z = float64(1)
for {
if d := (z*z - x)/z/2; math.Abs(d) < Delta {
break
} else {
z -= d
}
}
}
return z, err
}
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