c4se記:さっちゃんですよ☆

.。oO(さっちゃんですよヾ(〃l _ l)ノ゙☆)

.。oO(此のblogは、主に音樂考察Programming に分類されますよ。ヾ(〃l _ l)ノ゙♬♪♡)

音樂は SoundCloud に公開中です。

考察は現在は主に Scrapbox で公表中です。

Programming は GitHub で開發中です。

#golang §46 Advanced Exercise: Complex cube roots

A Tour of Go chapter 46

Advanced Exercise: Complex cube roots

Let's explore Go's built-in support for complex numbers via the complex64 and complex128 types. For cube roots, Newton's method amounts to repeating:
z = z - (z ** 3 - x) / (z * z * 3)
Find the cube root of 2, just to make sure the algorithm works. There is a Pow function in the math/cmplx package.

Example

 package main

import (
	"fmt"
	"math/cmplx"
)

func Cbrt(x complex128) complex128 {
	var z, prez complex128 = x / 3, 0
	for cmplx.Abs(z - prez) > 1e-10 {
		prez = z
		z = z - (z * z * z - x) / (z * z * 3)
	}
	return z
}

func main() {
	fmt.Println(Cbrt(2))
	fmt.Println(cmplx.Pow(Cbrt(2), 3))
}