Esempi: Lezione 4
Contents
Esempi: Lezione 4¶

4.0 utilizzo di `rand ()`
¶
/*
c++ -o main_00 main_00.cpp
*/
#include <cstdlib>
#include <iostream>
int main (int argc, char ** argv)
{
for (int i = 0 ; i < 5 ; ++i)
std::cout << "indice " << i << " --> " << rand () << "\n" ;
std::cout << "\nRAND_MAX: " << RAND_MAX << std::endl ;
return 0 ;
}

4.1 utilizzo di `srand ()`
¶
/*
c++ -o main_01 main_01.cpp
*/
#include <cstdlib>
#include <iostream>
#include <ctime>
int main (int argc, char ** argv)
{
srand (3) ;
for (int i = 0 ; i < 5 ; ++i)
std::cout << "indice " << i << " --> " << rand () << "\n" ;
std::cout << "\n" ;
srand (time (NULL)) ;
for (int i = 0 ; i < 5 ; ++i)
std::cout << "indice " << i << " --> " << rand () << "\n" ;
return 0 ;
}

4.2 generazione di pdf uniforme¶
/*
c++ -o main_02 main_02.cpp
*/
#include <cstdlib>
#include <iostream>
float rand_range (float min, float max)
{
return min + (max - min) * rand () / static_cast<float> (RAND_MAX) ;
}
int main (int argc, char ** argv)
{
for (int i = 0 ; i < 5 ; ++i)
std::cout << "indice " << i << " --> " << rand_range (-4., 4.) << "\n" ;
std::cout << "\n" ;
return 0 ;
}

4.3 generazione di pdf con il metodo try-and-catch¶
/*
c++ -o main_03 main_03.cpp
*/
#include <cstdlib>
#include <iostream>
#include <cmath>
float fgaus (float x)
{
return exp (-0.5 * x * x) ;
}
float rand_range (float min, float max)
{
return min + (max - min) * rand () / static_cast<float> (RAND_MAX) ;
}
float rand_TAC (float f (float), float xMin, float xMax, float yMax)
{
double x = 0. ;
double y = 0. ;
do {
x = rand_range (xMin, xMax) ;
y = rand_range (0, yMax) ;
} while (y > f (x)) ;
return x ;
}
int main (int argc, char ** argv)
{
for (int i = 0 ; i < 5 ; ++i)
std::cout << "indice " << i << " --> " << rand_TAC (fgaus, -1., 1., 1.) << "\n" ;
return 0 ;
}

4.4 generazione di pdf con il metodo del teorema centrale del limite¶
/*
c++ -o main_04 main_04.cpp
*/
#include <cstdlib>
#include <iostream>
#include <cmath>
float fgaus (float x)
{
return exp (-0.5 * x * x) ;
}
float rand_range (float min, float max)
{
return min + (max - min) * rand () / static_cast<float> (RAND_MAX) ;
}
float rand_TCL (float xMin, float xMax, int N = 10)
{
double y = 0. ;
for (int i = 0 ; i < N ; ++i)
y += rand_range (xMin, xMax) ;
y /= N ;
return y ;
}
int main (int argc, char ** argv)
{
for (int i = 0 ; i < 5 ; ++i)
std::cout << "indice " << i << " --> " << rand_TCL (-1., 1., 10) << "\n" ;
return 0 ;
}
