Skip to content

Instantly share code, notes, and snippets.

@athom
Created July 16, 2013 14:17
Show Gist options
  • Save athom/6009124 to your computer and use it in GitHub Desktop.
Save athom/6009124 to your computer and use it in GitHub Desktop.
牛顿迭代闭包版
package main
import (
"fmt"
"math"
"math/cmplx"
)
func equal(x, y complex128) bool {
delta := 0.000001
r1, t1 := cmplx.Polar(x)
r2, t2 := cmplx.Polar(y)
return math.Abs(r1-r2) < delta && math.Abs(t1-t2) < delta
}
func Y(x complex128) (r func(a complex128) (r2 complex128)) {
return func(z complex128) (r complex128) {
r = z - (cmplx.Pow(z, 3)-x)/(3*cmplx.Pow(z, 2))
return
}
}
func Cbrt(x complex128, f func(a complex128) (r complex128)) complex128 {
if equal(f(x), x) {
return x
}
return Cbrt(f(x), f)
}
func main() {
fmt.Println(Cbrt(2, Y(2)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment