1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CERN ROOT (C++) グラフ作成 (2) yをxの計算式として与え、x-yグラフを描画 (class TF1 )

Posted at

概要

xの値の範囲を決め、そのxに対する計算式または関数を指定してx-yグラフを描画する。
これにはCERN ROOTのclass TF1を使う。

実行環境

sw_vers
ProductName:		macOS
ProductVersion:		14.6.1
BuildVersion:		23G93

root --version
ROOT Version: 6.32.06
Built for macosxarm64 on Sep 21 2024, 18:21:53
From tags/6-32-06@6-32-06

計算式を文字列で与える

root [0] auto tf = new TF1("sin","TMath::Sin(x)", 0,10);
root [1] tf->Draw();
Info in <TCanvas::MakeDefCanvas>:  created default TCanvas with name c1
root [2]

2024-10-30 18.45.32.png

"TMath::Sin(x)"が計算式です。2次関数なら"x*x+3*x+1"となどとできます。ROOTで使える関数ならいろいろな関数を含めた計算式が指定できます。
第3、4の引数がxの値の範囲です。
また、計算した(x,y)の点をマーカーで表示したい場合は次のようにします。

root [0] auto tf = new TF1("sin","TMath::Sin(x)", 0,10);
root [1] tf->SetMarkerStyle(20);
root [2] tf->Draw("pl");
Info in <TCanvas::MakeDefCanvas>:  created default TCanvas with name c1
root [3]

2024-10-30 18.56.38.png
計算しているx座標の数を指定することが次のようにするとできます。

root [3] tf->SetNpx(30);

Drawを実行しなくても即座にグラフへ反映されます。マーカーを数えたら30有りました。

2024-10-30 19.04.56.png

パラメータ付き計算式

2次関数$ax^2+bx+c$の$a,b,c$をパラメータとする。

root [0] auto tf = new TF1("xx","[0]*x*x+[1]*x+[2]", -10,10);
root [1] tf->SetParameters(1,-2,-10);
root [2] tf->Draw();
Info in <TCanvas::MakeDefCanvas>:  created default TCanvas with name c1
root [3]

[0],[1],[2]がそれぞれ$a,b,c$を表している。SetParametersの引数が順番に
[0],[1],[2]へ値を設定している。Drawの後にSetParametersで値を変更すると即座にグラフが更新される。また、個別にパラメータを変更したい場合はtr->SetParameter(0,3);とすると[0]の値が3に変更されグラフも更新される。

2024-10-30 19.56.45.png

計算式をCの関数として定義

上記と同様の2次関数をCの関数で計算する例を示します。

root [0] Double_t func(Double_t *x, Double_t *p){Double_t xx = *x; return p[0]*xx*xx+p[1]*xx+p[2];}
root [1] auto tf = new TF1("xx",func, -10,10, 3);
root [2] tf->SetParameters(1,-2,-10);
root [3] tf->Draw();
Info in <TCanvas::MakeDefCanvas>:  created default TCanvas with name c1
root [4]

計算する関数をDouble_t 関数名(Double_t *x, Double_t *p)として定義します。TF1の第5引数の値の数だけのパラメータをSetParamtersなどで設定した値が pに渡されます。パラメータが無いときは第5引数に0指定するか省略します。

2024-10-30 20.39.57.png

終わりに

使用は限定されますが、TGraphより簡便に使えます。また、計算式の設定の仕方は上記以外にも幾つかあります。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?