- Real algebra: scalar product, matrix-vector product
- Armadillo library
- Real RCDS problems: Rectilinear movement, estimate Higgs mass, umerical integration.
Before starting we suggest to create a folder for Chapter 6 where you can save all files that will be created for the exercise
cd ~/ # Go the home directory
mkdir Chapter6 # Create the directory Chapter6
cd Chapter6 # Go inside Chapter6
Create a makefile
with targets:
all
: compile all programs in this folder.clean
: delete all programs created byall
.
Example of makefile
:
all: program1
program1: exercise1.cc
g++ exercise1.cc -o program1
# also: g++ $< -o $@
clean:
rm program1
in this way all programs will be compiled using the following command in the terminal:
$ make
while all programs will be eliminated by using the folloing one:
$ make clean
Write a C++ program that computes the scalar product using dynamic arrays.
-
Build the precedent vectors
v
andw
using dynamic arrays. Remember to allocate them using the operatornew
and delete them withdelete
. -
Create an array
s
as the sum ofv
andw
. -
Print the elemnts of
s
.
Write a C++ program that computes the scalar product using dynamic arrays.
-
Build the precedent vectors
v
andw
using dynamic arrays. Remember to allocate them using the operatornew
and delete them withdelete
. -
Implement the scalar product between
v
andw
and print the result. -
Create a vector
z
equal tov
(same dimension and copy of the content) withz[2] = 0
. -
Compute the normalization of
z
. -
Normalize
z
and print its values on the terminal.
Write a C++ program that compute a matrix-vector product.
-
Create stack arrays for all objects, i.e.
x
,M
,v
, write the matrices that that composeM
in two different arraysA
eB
. -
Compute
M
applying the matrix product betweenA
andB
. -
Compute the product
M * x
. -
Print the result and verify the solution
r = {34, 39, 7}
.
Write a C++ program that computes the following algebra operations.
-
Create a 2 1D arrays of type
double
withv = {1, 2, 3, 4, 5}, w = {10, 2, 4, 3, 2}
. Create a 2D array of typedouble
withM = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
. -
Implement a function
scalar
of typedouble
that computes the scalar product between 2 arrays. Test the function withv
andw
and print the result on screen. -
Implement a function
norm
of typedouble
that computes the norm of an array using the functionscalar
. Test the implementation ofv
and print the result on screen. -
Implement a function
change
of typevoid
that changes the values between 2 objects by reference. Apply this function toM
(e.g. compute the transpose) and print the result on screen.
Write a C++ program where complex numbers are saved as data structure
-
Create a data structure called
complex
. Inside thisstruct
implement two members of typedouble
,real
for the real part, andimag
for the imaginary one. -
Write a the function
main
and declare 2 variables of typecomplex
calleda
andb
respectively. -
Assign to
a
the complex number7 + 2i
. -
Assign to
b
the value ofa
. -
Implement a function tha takes a
complex
and prints on terminal the real and imaginary part separated by a coma. -
Use the function above for printing the content of
a
andb
. -
Implement a function
module
of typedouble
that computes the module of acomplex
. Test the function directly on the main passinga
as argument. -
Implement a function
sum
of typecomplex
thakes as arguments 2 objectscomplex
and returns a newcomplex
where the real and imaginary parts correspond to those of the sum of the arguments.
Write a program in C++ that solves a second order equation a x^2 + b x + c = 0
for all discriminants (>, < e = 0) and where the variables a
, b
e c
come assigned with cin
.
-
Ask the user to introduce 3 numbers of type
double
representing the coefficients. -
Compute the discriminant
D = b^2 - 4ac
using the functionstd::pow
. -
Create a condition
if/else
corresponding to the 3 possible cases of the discriminant. -
Compute the solutions
x1
andx2
using the quadratic formula for second order equations. Note that forD < 0
, the functionstd::sqrt()
operates in the real numbers, therefore its argument must be a positive number. Also in this case we will separe the computations of the real and imaginary part.
Verify the implementation for the following coefficients:
a = 2
,b = 5
,c = 2
-> solutionx1 = -0.5
ex2 = -2
.a = 4
,b = -4
,c = 1
-> solutionsx1,2 = 0.5
.a = 1
,b = 4
,c = 5
-> solutionsx1 = -2 + i
ex2 = -2 - i
.
Armadillo is a linear algebra library for C++ which uses syntax quite similar to that used in Matlab or Python (with NumPy). Setup is different for different operating systems but the instructions are pretty good.
Here we are going to just include the library directly by downloading and linking to the library files. This doesn't take advantage of your computer's inbuilt fast linear algebra libraries, but it is enough for our purposes.
Installation
- Download the Armadillo zip file from this GitHub repository.
- Extract it to the folder
armadillo-9.870.2
in yourcpp
folder.
Join in:
- New file:
armadillo_test.cpp
:
#include <iostream>
#include <armadillo>
using namespace std;
using namespace arma;
int main()
{
arma_rng::set_seed_random();
mat A = randu<mat>(4,5);
mat B = randu<mat>(4,5);
cout << A*B.t() << endl;
return 0;
}
Compile:
-
(On your own Mac/Linux machine)
c++ armadillo_test.cpp -o armadillo_test -I path_to_armadillo_include -llapack -lblas
-
(On college machines or your own Windows machine)
g++ armadillo_test.cpp -o armadillo_test -I path_to_armadillo_include -llapack -lblas -static-libstdc++
-
New file:
armadillo_equations.cpp
:
Let's solve the system of equations
- x + 5z = –1
- 2x + y + 6z = 0
- 3x + 4y = 1
#include <iostream>
#include <armadillo>
using namespace std;
using namespace arma;
int main()
{
mat A = mat("1 0 5; 2 1 6; 3 4 0");
mat b = mat("-1; 0; 1");
mat x;
x = solve(A,b);
cout << x << endl;
return 0;
}
Compile:
- (On your own machine)
c++ armadillo_equations.cpp -o armadillo_equations -Ipath_to_armadillo_include -llapack -lblas
- (On college machines or your own Windows machine)
g++ armadillo_equations.cpp -o armadillo_equations -I path_to_armadillo_include -llapack -lblas -static-libstdc++
We should get the solution: x = 19, y = –14, z = –4.
Write a C++ program that reads space and time coordinates of a falling particle from a file, computes the instant velocity for each measurement and the mean velocity, its standard deviation, the minimum and maximum values
- Download the data with:
wget https://github.com/ImperialCollegeLondon/RCDS-intro-cpp/blob/main/Chapter6/data_moto.dat
-
Read from the file the
N = 1000
(number of elements) points (x y) with the space (km) and times (h), and compute for each element the instant velocity. Save those values in an array of typedouble
. -
Compute the mean velocity, the standard deviation and print the results on screen.
-
Compute the minimum and maximum velocity, and print the results on screen.
-
Verify the results.
Write a C++ program that reads from a file the distribution of invariant mass for the production channel of 4 leptons to Higgs, measured at the ATLAS detector, and determine the most frequent (most likely) value for the mass.
La distribuzione in questione si presenta graficamente nel modo seguente:
- Download data with:
wget https://github.com/ImperialCollegeLondon/RCDS-intro-cpp/blob/main/Chapter6/data_higgs.dat
-
Read all
N = 10000
values of invariant mass and save the data in an arraymass
. -
Order the vector
mass
in increasing way using sort selection. (Control the algorithm printing on the values on screen) -
Extract the minimum and maximum values directly from
mass
(without loops or extra algorithms). Print the values on terminal. -
Build an array
bins
that contains upper and lower edge of an histogram that begins with the mimimum value of the mas and increases in steps of 5 GeV. Hiny: determine the number of bins needed and create a dynamic array for the binning. -
Build an array
freq
for the frequences of the histogram. -
Fill the histogram and print the values of the bins and frequence on screen.
-
Determine the bin (lower-edge) of Higgs mass with highest frequence.
Write a C++ program that computes the numerical integral of an analytical function usin the trapezoidal rule
/b
| f(x) dx = d * Sum_{i=0,n-1} ( f(a + i * d) + f(a + (i + 1) * d) ) / 2
/a
where d = (b-a)/n
.
- Implement a function
gauss
of typedouble
that replaces tha value of a normalized Gaussian centered inmu = 0
andsigma = 1
:
gauss(x) = 1/(sqrt(2*pi)) * exp(-x*x/2)
-
Implement a function
integrate_gaussian
of typedouble
that takes argumentsa
,b
andn
(steps), and computes the integral ofgauss
betweena
andb
. -
Test the function for
(a,b) = (-10, 10)
and(a,b) = (-1,1)
, for each configuration changen = [10,100]
.