Created
July 14, 2013 06:06
-
-
Save MattSurabian/5993362 to your computer and use it in GitHub Desktop.
My implementation of the Newtonian Cube Root Approximation using complex numbers in Go. Part of the Go tour: http://tour.golang.org/#47
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" | |
import "math/cmplx" | |
import "math" | |
const( | |
ACCURACY_DELTA = 0.0000000000000001 | |
) | |
func Cbrt(x complex128) complex128 { | |
ourGuess := complex128(1) // any initial guess will do! | |
for newtonGuess := newtonIteration(x, ourGuess); cmplx.Abs(newtonGuess-ourGuess) > ACCURACY_DELTA | |
{ | |
ourGuess = newtonGuess; | |
newtonGuess = newtonIteration(x, ourGuess) | |
} | |
return ourGuess | |
} | |
func newtonIteration(x, z complex128) complex128{ | |
return z-(cmplx.Pow(z,3)-x)/cmplx.Pow(3*z,2) | |
} | |
func main() { | |
fmt.Println("Newtonian Complex Cube Root:", Cbrt(2)) | |
fmt.Println("Non-Complex Control:", math.Cbrt(2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment