【C言語】 complex.h を使った複素数計算【標準ライブラリ】

【C言語】 complex.h を使った複素数計算【標準ライブラリ】

complex.h とは

C言語の complex.h は、C99 以降で標準ライブラリに追加されたヘッダーファイルで、複素数を扱うための関数や型を提供します。 これにより、C言語で簡単に複素数の加減乗除、絶対値、偏角、三角関数などの演算を行うことができます。

基本的な使い方

complex.h を使用するには、以下のようにヘッダーをインクルードします。

#include <complex.h>
#include <stdio.h>

int main() {
    double complex z = 1.0 + 2.0 * I;
    printf("実部: %f\n", creal(z));
    printf("虚部: %f\n", cimag(z));
    return 0;
}

ここで、I は虚数単位(i)の定義で、creal() は実部を、cimag() は虚部を取得する関数です。

複素数の演算

complex.h では、複素数の基本的な演算が可能です。

加算と減算

#include <complex.h>
#include <stdio.h>

int main() {
    double complex z1 = 1.0 + 2.0 * I;
    double complex z2 = 3.0 + 4.0 * I;
    
    double complex sum = z1 + z2;
    double complex diff = z1 - z2;

    printf("和: %f + %fi\n", creal(sum), cimag(sum));
    printf("差: %f + %fi\n", creal(diff), cimag(diff));

    return 0;
}

乗算と除算

#include <complex.h>
#include <stdio.h>

int main() {
    double complex z1 = 1.0 + 2.0 * I;
    double complex z2 = 3.0 + 4.0 * I;
    
    double complex prod = z1 * z2;
    double complex quot = z1 / z2;

    printf("積: %f + %fi\n", creal(prod), cimag(prod));
    printf("商: %f + %fi\n", creal(quot), cimag(quot));

    return 0;
}

複素数を扱う数学関数

complex.h には、さまざまな数学関数が用意されています。

絶対値(ノルム)

#include <complex.h>
#include <stdio.h>
#include <math.h>

int main() {
    double complex z = 3.0 + 4.0 * I;
    printf("絶対値: %f\n", cabs(z));
    return 0;
}

偏角(アーギュメント)

#include <complex.h>
#include <stdio.h>
#include <math.h>

int main() {
    double complex z = 1.0 + I;
    printf("偏角: %f\n", carg(z));
    return 0;
}

三角関数

#include <complex.h>
#include <stdio.h>
#include <math.h>

int main() {
    double complex z = I;
    printf("sin(z): %f + %fi\n", creal(csin(z)), cimag(csin(z)));
    printf("cos(z): %f + %fi\n", creal(ccos(z)), cimag(ccos(z)));
    return 0;
}

応用例

フーリエ変換

フーリエ変換では、複素数の指数関数を多用します。例えば、ある信号の離散フーリエ変換(DFT)の計算に complex.h を活用できます。

電気回路のシミュレーション

電気回路の交流解析では、インピーダンスの計算に複素数が必要です。例えば、以下のようにコンデンサとインダクタのインピーダンスを求めることができます。

#include <complex.h>
#include <stdio.h>
#include <math.h>

int main() {
    double f = 50.0; // 周波数 (Hz)
    double L = 0.1;  // インダクタンス (H)
    double C = 1e-6; // キャパシタンス (F)
    
    double complex Z_L = I * 2.0 * M_PI * f * L;
    double complex Z_C = -I / (2.0 * M_PI * f * C);

    printf("インダクタンスのインピーダンス: %f + %fi\n", creal(Z_L), cimag(Z_L));
    printf("キャパシタンスのインピーダンス: %f + %fi\n", creal(Z_C), cimag(Z_C));

    return 0;
}

まとめ

complex.h を使うことで、C言語でも簡単に複素数の計算ができます。基本的な演算から数学関数、応用例まで紹介しましたが、特に科学技術計算では非常に便利です。

コメントは受け付けていません。