Fork me on GitHub

cuspy memo


リュカ数をプロットする

2008/03/05 Wednesday 04:42:41

この前フィボナッチ関数のグラフを gnuplot で描いた時に sakaik さんから詳しい書き方を聞かれたので、今回はリュカ数をプロットしてその手順を詳しく書いてみる。

リュカ数列とは、フィボナッチ数列が

F_0=0
F_1=1
F_{n+2}=F_n + F_{n+1}

と定義されるのに対し初期値を

F_0=2
F_1=1

とした時の数列をリュカ数列と呼ぶらしい。see リュカ数 – Wikipedia
具体的には

2, 1, 3, 4, 7, 11, 18, 29

みたいな感じ。
この数列を実数(複素数)の世界に拡張して、入力を z(レンジは -5 〜 5), 出力の実部を x 軸, 虚部を y 軸にプロットしてみる。

ソースコード(lucas.c)

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

#define THETA 1.618034

double complex clucas(double i)
{
    double complex c = cpow(-THETA, -i);
    return (pow(THETA, i) + creal(c)) + cimag(c) * I;
}

void plot_clucas(double min, double max)
{
    double z;
    double complex c;
    for(z=min; z<max; z+=0.1){
        c = clucas(z);
        printf("%lf\t%lf\t%lf\n", creal(c), cimag(c), z);
    }
}

int main(int argc, char *args[]){
    plot_clucas(-5, 5);
    return EXIT_SUCCESS;
}

これをコンパイルして実行する

% gcc -lm lucas.c -o lucas
% lucas > lucas.dat

次にこんな感じの plt ファイル(lucas.plt)を用意して

set term png
set output "lucas.png"
splot "lucas.dat" with lines

gnuplot を実行すると・・・

% gnuplot lucas.plt

グラフの出来上がり!

lucas

ついでなので fibonacci 関数と混ぜてみる。

merge

赤がリュカ数で緑がフィボナッチ。

  1. Robert wrote related post…

    Silk posts and stories…

    Trackback by Robert wrote related post — 2008/06/19 Thursday @ 22:07:54

Leave a comment

You must be logged in to post a comment.