LoginSignup
13
8

More than 5 years have passed since last update.

golang complex(複素数)型を使う

Last updated at Posted at 2016-10-12

golang

goには、complex(64 or 128)型というものがあります。
complexとは複素数のことです。

初めに

難しいのでむやみに使うとわかりづらいコードになります。

複素数型リテラル

floatのリテラルの末尾にiを付けます。

c := 1i
fmt.Println("%T, %v", c, c)  //表示[complex128, 0+1i]

省略しないリテラルは0+1iのようですね。
また、型はデフォルトでcomplex128のようです。

型の変換

もちろん実数型と互換性があります。

var c complex128 = complex(1, 2) // 複素数に変換
var fr float64 = real(c) // 実数に戻す
var fi float64 = imag(c) // 実数に戻す
fmt.Println(fr, fi)  //表示[1 2]

関数みたいに書くと

・実数→複素数
complex(real, imag float)complex

・複素数→実数
real(c complex)float
imag(c complex)float

といった感じです
(float32,64はそれぞれcomplex64,128に対応します)

標準パッケージ

https://golang.org/pkg/math/cmplx/
import "math/cmplx"
これで標準パッケージが使えます。

mathパッケージにもあるような便利な関数が入っています。
cmplx.Log()
cmplx.Pow()
cmplx.Sin()
などなど。

golang complex(複素数)型の計算をする

13
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
8