Created
July 13, 2012 23:35
-
-
Save freeformz/3108235 to your computer and use it in GitHub Desktop.
My GoTour Exercise #48 (http://tour.golang.org/#48) solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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