Skip to content

Instantly share code, notes, and snippets.

@freeformz
Created July 13, 2012 23:35
Show Gist options
  • Save freeformz/3108235 to your computer and use it in GitHub Desktop.
Save freeformz/3108235 to your computer and use it in GitHub Desktop.
My GoTour Exercise #48 (http://tour.golang.org/#48) solution
package main
import (
"fmt"
"math"
"math/cmplx"
)
func cbrt(target, guess complex128) complex128 {
return guess - (cmplx.Pow(guess, 3)-target)/(3*cmplx.Pow(guess,2))
}
func inequiv(a, b complex128) bool {
//This is probably cheating
return math.Nextafter(real(a), real(b)) != real(b)
}
func Cbrt(x complex128) complex128 {
curr, guess := complex128(0), complex128(10)
for inequiv(curr, guess) {
curr = cbrt(x, guess)
guess = (curr + guess) / 2
}
return guess
}
func main() {
fmt.Println(Cbrt(2))
fmt.Println(math.Cbrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment