第15章練習問題5

  • 投稿日:
  • by
  • カテゴリ:

 この章で、関数をグラフ化する方法とか、ラムダ式の書き方とかを勉強。練習問題5をやることにした。

1-1/3+1/5-1/7+1/9-1/11+・・・をアニメーションにする。これは「ライプニッツの級数」と呼ばれ、π/4に収束する。

 軸の描き方とか、いろいろ面倒な用意をする必要がある。πの値は、#define _USE_MATH_DEFINESを宣言しておくと、M_PIで値が定義されているようである。
 アニメーションといっても、単一の値が収束していくだけである。級数の添え字をnとし、nの値をX軸にして、その時の級数の値をy軸に表示するような構成にしてみた。あまり面白い表示にはなっていないが、一応、私の作った例は下記の通り。


#define _USE_MATH_DEFINES
#include "Simple_window.h"
#include "Graph.h"

double leibniz(int n) {
    double r = 1;
    while (n > 0) {
        if (n % 2 == 0) r += 1.0 / (2.0 * n + 1.0);
        else r -= 1.0 / (2.0 * n + 1.0);
        --n;
    }
    return r;
}

 

int main()
{
    using namespace Graph_lib;

    constexpr int xmax = 600;
    constexpr int ymax = 400;

    constexpr int margin = 40;

    constexpr int xlength = xmax - margin;
    constexpr int ylength = ymax - margin;

    constexpr int x_orig = margin;
    constexpr int y_orig = ymax- margin;
    const Point orig{ x_orig,y_orig };

    constexpr int nmax = 50;

    constexpr double x_scale = xlength / nmax;
    constexpr double y_scale = (ylength-margin) / 5.0 * 4.0; //縦軸を0.25刻みで5個分取る

    Simple_window win{ Point{100,100},xmax,ymax,"Functopn graphing" };

    Axis x{ Axis::x,Point{ margin,y_orig },xlength,nmax,"one notch = 1" };
    Axis y{ Axis::y,Point{ x_orig,ylength },ylength - margin,5,"one notch =0.25" };
    x.set_color(Color::red);
    y.set_color(Color::red);
    win.attach(x);
    win.attach(y);

    Function pi4([](double x) {return M_PI / 4;}, 0, nmax, orig, 200, x_scale, y_scale); // pi/4
    pi4.set_color(Color::blue);
    win.attach(pi4);

    for (int n = 1;n < 50;++n) {
        ostringstream ss;
        ss << "Leibniz; n=" << n;
        win.set_label(ss.str());

        double y;
        int xp,yp;

        xp = x_orig + n*x_scale;

        y = leibniz(n);
        yp = ylength - y*y_scale;

        Circle l{ Point{ xp, yp },2 };

        win.attach(l);

        win.wait_for_button();

        win.detach(l);
    }

}

 プログラムそのものよりも、ボタンを押す都度、画面が小さくなっていくという現象があって、解決に時間を取ってしまった。c++ - Stroustrup's "Simple_window" shrinks when pushing "Next" button - Stack Overflowで、ある環境でのみ生じるFLTKのバグであることがわかった。この記事では、FLTK1.3.3で解決済みとあったが、私の環境では、それでもだめで、1.4.2をダウンロードし、環境を再構築して、やっと動かすことができた。この手の問題は、勉強の本質の部分よりも時間が必要でやっかいだ。