# Computational Lab in Physics: Doing calculations in C++ and using ROOT.

Derivatives

Steven Kornreich www.beachlook.com

ROOT: http://root.cern.ch/

Using ROOT

Setting up ROOT in the Rm 106 linux cluster
 By

2

ROOT commands
 

Starting root, just type “root” At the root prompt:
  

.q = Exit from root .ls = list the files loaded into root session .! some-unix-command = execute some-unixcommand in the shell

Most c++ commands can also be interpreted. Executing a macro “myMacro.C”:

.x myMacro.C
3

ROOT Classes

Since it is C++, everything is represented by classes:
 

Windows (or canvases) : TCanvas

Functions : TF1, TF2, TF3

A window where we can draw data, functions, etc. Classes to manipulate mathematical functions, such as sin(x), in order to draw, evaluate, and integrate them. Class used to plot data on a canvas Classes to manipulate histograms. Can draw them on a canvas, integrate them, obtain means and RMS values, evaluate bin contents.

 

Graphs : TGraph

Histograms: TH1, TH2, TH3

4

Derivatives
df  f ( x  x)  f ( x)   lim   x  0 dx x  
Forward difference operator

 f ( x  x)  f ( x)  D (f)  x  
 x
5

What is the order of the error?

Use Taylor expansion.

6

Example code: derivative operator.
int main() { double del = 1.0e-1; int choice; cout << "Choose a function:" << endl; cout << "1) cube " << endl; cout << "2) linear " << endl; cin >> choice; switch (choice) { case 1: cout << derivOperator(cube,1.0,del) << endl; break; case 2: cout << derivOperator(linear,1.0,del) << endl; break; default: cout << "Incorrect input, exiting." << endl; } return 0; }
7

Output:
[mcalderon@born YevickChapter12]\$ derivOperatorExample Choose a function: 1) cube 2) linear 2 1 [mcalderon@born YevickChapter12]\$ derivOperatorExample Choose a function: 1) cube 2) linear 1 3.31

8

Error dependence

Note: the “approximation” is actually exact for the linear case.
 Error

estimation for linear case is misleading.

When del is small, rounding errors degrade the accuracy.
 double

variables can do ~14 sig. figs.  what happens if del=1.0e-17?

9

Graphical error analysis

For the finite difference case, we know dependence through Taylor series. Other times, dependence must be obtained empirically.
 Method:

determine the variation in the result when changing the step size and plot a graph.

10

Plotting with ROOT: Split into two parts:

Make a program that writes the data into a text file. Only use c++ standard libraries. Read the data from a ROOT session, and create the necessary TGraph, TH1, etc. One can do both in one step, but must take care to include the ROOT libraries and link with them.
 

For some reason, does not work in the 106 cluster… However above solution works.

11

Sample code, Part I:
#include <cmath> #include <iostream> #include <fstream> using namespace std; double cube (double aD) { return pow(aD,3); } double linear(double aD) { return pow(aD,1); } double derivOperator(double f(double), double aX, double aDel) { return ( f(aX+aDel) - f(aX) )/aDel; }
int main() { double del = 1.0e-1; ofstream ofs("outputFile.txt"); ofs << "X Y" << endl; float x[10], y[10]; // arrays holding 10 floats for (int i=0; i<10; ++i) { y[i] = derivOperator(cube, 1.0, del); // Derivative for a given value of del x[i] = del; del /=2.0; // decrease the value of del by factor 2 ofs << x[i] << '\t' << y[i] << endl; } ofs.close(); } return 0;

12

void plotDataErrorDeriv() { ifstream ifs("outputFile.txt"); string dummy; ifs >> dummy >> dummy; float x[10], y[10]; for (int i=0; i<10; ++i) { ifs >> x[i] >> y[i]; cout << x[i] << '\t' << y[i] << endl; } TGraph* theGraph = new TGraph(10,x,y); theGraph->SetMarkerStyle(20); theGraph->Draw("APL"); // Draw options: // A : Axes // P : polymarker // L : Line // X axis title theGraph->GetXaxis()->SetTitle("Step Length"); // Y axis title theGraph->GetYaxis()->SetTitle("Error"); return; }
13

Using TGraph, TF1 and TCanvas…
Plot obtained from program in section 12.3:

Evaluating derivative operator vs step length.

14

Graph Draw Options
The various draw options for a graph are explained in TGraph::PaintGraph. They are: • "L" A simple poly-line between every points is drawn • "F" A fill area is drawn • “F1” Idem as "F" but fill area is no more repartee around X=0 or Y=0 • "F2" draw a fill area poly line connecting the center of bins • "A" Axis are drawn around the graph • "C" A smooth curve is drawn • "*" A star is plotted at each point • "P" The current marker of the graph is plotted at each point • "B" A bar chart is drawn at each point • "[]" Only the end vertical/horizontal lines of the error bars are drawn. This option only applies to the TGraphAsymmErrors. • "1" ylow = rwymin The options are not case sensitive and they can be concatenated in most cases. Let us look at some examples

15

For Homework: Derivatives
Chapter 12, Section 12.7 Use root for the plots.  Assigment 1 Explore higher order methods. For discussing the power behavior, use a log plot in root and show that the slope is 4. To set log or log-log plots, which are needed for the assignment, you need to invoke the TCanvas::SetLogy() and TCanvas::SetLogx() commands. You can create a canvas in root by using e.g. TCanvas myCanvas("myCanvas","Canvas For Hwk 2",500,500), and then use myCanvas.SetLogy(1) and myCanvas.SetLogx(1).

Assignment 2 Apply program from Assignment 1 it to f(x) = x4. Discuss the behavior and put your comments in a text file, for example "hwk2Discussion.txt" in the corresponding hwk2 directory.

16

17

Plotting simple functions in ROOT

Using TF1
 write

explicitly the function in the 2nd argument  E.g. Aebt + Ce-dt
TF1* myFunc = new TF1(“myFunc",”[0]*exp([1]*x)+[2]*exp([3]*x)”,0,10);

18

Plotting a user defined function in ROOT
double mysine(double* x, double* par) { double Amplitude = par[0]; double wavelength = par[1]; double phase = par[2]; return Amplitude*sin(2*TMath::Pi()/wavelength*x[0]+phase); } void plotsine() { TCanvas* sineCanvas = new TCanvas("sineCanvas","A*sin(2pi/lambda*x + phi)",500,500); TF1* sineFunc = new TF1("sineFunc",&mysine,0,2*TMath::Pi(),3); sineFunc->SetParameters(2,TMath::Pi(),TMath::Pi()/2); sineFunc->Draw(); return;

}

19

Result of plotting TGraph

Data points are plotted by TGraph Line is plotted using TF1
 Dotted:

1st order interpolation  Blue line: 2nd order interpolation.
20

Resources for ROOT

ROOT Web page:

http://root.cern.ch/ http://root.cern.ch/root/doc/RootDoc.html

User guides

21