数値計算の結果をプロットする(1)

まずは次の簡単な関数を数値計算で解いてみましょう。ここではC言語を用います。

f(x) = (x^3)/2 - x^2 + 20*x

ただし求めるxの範囲は -10 <= x <= 10とし,xが0.1増加するごとにf(x)の値を求めるようにします。

以下がそのプログラムです。

nc1.c

/* Numeral Computing with gnuplot: 1 */

#include <stdio.h>

int main(void);

int main(void) {
  int n;     /* ステップ数 */
  double x;  /* ステップ n における x の値 */
  double y;  /* x における y の値 */

  for (n=-100; n<=100; n++) {
    x = (double)n / 10;
    y = (x*x*x)/2 - x*x + 20*x;
    printf("%f %f\n", x, y);
  }

  return 0;
}

このCソースコードをコンパイルして,実行結果をnc1.pltに出力します。

% gcc -o nc1 nc1.c
% ./nc1 > nc1.plt

nc1.pltの中身は,次のようなデータが201行並んでいます。

nc1.plt

-10.000000 -800.000000
-9.900000 -781.159500
-9.800000 -762.636000
-9.700000 -744.426500
-9.600000 -726.528000
(以下略)

それではgnuplotでデータをプロットしてみましょう。

# 結果

gnuplot> cd 'd:\tmp'         # nc1.pltがあるディレクトリに移動(各自適当に)
gnuplot> plot 'nc1.plt' w l

この他,with dotsでプロットしてみたり,gnuplotの描画機能でf(x)を重ねて描いてみましょう。

$Id: numeric_computing1.shtml 1289 2007-02-04 13:22:39Z SYSTEM $