Go/complex
表示
< Go
complex() は実部と虚部から複素数値を構成する組み込み関数です。
宣言
[編集]func complex(r, i FloatType) ComplexType
引数 r が実部、i が虚部です。
両引数は同じ浮動小数点型でなければなりません。
戻り値の型は引数の型によって決まります。
| 引数の型 | 戻り値の型 |
|---|---|
float32
|
complex64
|
float64
|
complex128
|
| 型なし定数 | complex128(デフォルト)
|
基本的な使い方
[編集]c1 := complex(3.0, 4.0) // (3+4i) complex128 c2 := complex(float32(1.0), float32(2.0)) // (1+2i) complex64 fmt.Println(c1) // (3+4i) fmt.Println(c2) // (1+2i)
複素数リテラルを使って直接書くこともできます。
c := 3.0 + 4.0i // complex128
| 引数の型 | real / imag の戻り値の型 |
|---|---|
complex64
|
float32
|
complex128
|
float64
|
c := complex(3.0, 4.0) c == complex(real(c), imag(c)) // true
演算
[編集]複素数型は四則演算と等値比較をサポートしています。
a := complex(1.0, 2.0) // (1+2i) b := complex(3.0, 4.0) // (3+4i) fmt.Println(a + b) // (4+6i) fmt.Println(a - b) // (-2-2i) fmt.Println(a * b) // (-5+10i) fmt.Println(a / b) // (0.44+0.08i) fmt.Println(a == b) // false
math/cmplx パッケージ
[編集]複素数向けの数学関数は標準ライブラリの math/cmplx パッケージに用意されています。
import "math/cmplx" c := complex(3.0, 4.0) fmt.Println(cmplx.Abs(c)) // 5(絶対値) fmt.Println(cmplx.Phase(c)) // 0.9272952180016122(偏角、ラジアン) fmt.Println(cmplx.Conj(c)) // (3-4i)(共役複素数) fmt.Println(cmplx.Sqrt(c)) // (2+1i)(平方根) fmt.Println(cmplx.Exp(c)) // (-13.128783081462158+15.200784463067954i)(指数関数)
ゼロ値
[編集]complex64 のゼロ値は (0+0i)、complex128 のゼロ値も (0+0i) です。
var c complex128 fmt.Println(c) // (0+0i)