Sei sulla pagina 1di 21

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 default, root is not in your path.
 To add, add these lines to your
.bashrc:
 export ROOTSYS=/usr/local/root

 export PATH=$PATH:$ROOTSYS/bin

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-unix-
command 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
 A window where we can draw data, functions, etc.
 Functions : TF1, TF2, TF3
 Classes to manipulate mathematical functions, such
as sin(x), in order to draw, evaluate, and integrate
them.
 Graphs : TGraph
 Class used to plot data on a canvas
 Histograms: TH1, TH2, TH3
 Classes to manipulate histograms. Can draw them
on a canvas, integrate them, obtain means and
RMS values, evaluate bin contents.

4
Derivatives

df  f ( x  x)  f ( x) 
 lim  
dx x  0
 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.
#include <cmath> int main() {
#include <iostream> double del = 1.0e-1;
int choice;
cout << "Choose a function:" << endl;
using namespace std;
cout << "1) cube " << endl;
cout << "2) linear " << endl;
double cube (double aD) { cin >> choice;
return pow(aD,3); switch (choice) {
} case 1:
cout << derivOperator(cube,1.0,del) <<
double linear(double aD) { endl;
return pow(aD,1); break;
} case 2:
cout << derivOperator(linear,1.0,del)
<< endl;
double derivOperator(double f(double), break;
double aX, double aDel) {
default:
return ( f(aX+aDel) - f(aX) )/aDel; 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.
 Errorestimation for linear case is
misleading.
 When del is small, rounding errors
degrade the accuracy.
 doublevariables 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:
int main() {
#include <cmath> double del = 1.0e-1;
ofstream ofs("outputFile.txt");
#include <iostream>
ofs << "X Y" << endl;
#include <fstream>
float x[10], y[10]; // arrays holding 10
floats
using namespace std; for (int i=0; i<10; ++i) {
y[i] = derivOperator(cube, 1.0, del); //
double cube (double aD) { Derivative for a given value of del
return pow(aD,3); x[i] = del;
} del /=2.0; // decrease the value of del
by factor 2
ofs << x[i] << '\t' << y[i] << endl;
double linear(double aD) { }
return pow(aD,1); ofs.close();
}
return 0;
double derivOperator(double f(double), }
double aX, double aDel) {
return ( f(aX+aDel) - f(aX) )/aDel;
}
12
Reading in ROOT, plotting Graph:

void plotDataErrorDeriv() { TGraph* theGraph = new TGraph(10,x,y);


theGraph->SetMarkerStyle(20);
ifstream ifs("outputFile.txt"); theGraph->Draw("APL");
string dummy; // Draw options:
ifs >> dummy >> dummy; // A : Axes
float x[10], y[10]; // P : polymarker
for (int i=0; i<10; ++i) { // L : Line
ifs >> x[i] >> y[i];
cout << x[i] << '\t' << y[i] // X axis title
<< endl; 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/
 User guides
 http://root.cern.ch/root/doc/RootDoc.html

21

Potrebbero piacerti anche