Getting integer random values instead of real values using boost::random library - c++

I am trying to get real random values using boost::random libraries. This is my code:
#include <iostream>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
boost::random::mt19937 eng = boost::random::mt19937();
boost::random::uniform_real_distribution<double> urd =
boost::random::uniform_real_distribution<double>(0,20);
for (int i = 0; i <= 100; i++)
std::cout << urd(eng) << std::endl;
But I get integer numbers between 0 and 20.
How can I do?
I also tried another engine:
#include <iostream>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/lagged_fibonacci.hpp>
boost::random::lagged_fibonacci607 eng = boost::random::lagged_fibonacci607();
boost::random::uniform_real_distribution<double> urd =
boost::random::uniform_real_distribution<double>(0,20);
for (int i = 0; i <= 100; i++)
std::cout << urd(eng) << std::endl;
But nothing... (always integer values)

How about setting the precision before you output? std::cout.precision(15);?
Or use:
std::cout.precision(std::numeric_limits<double>::digits10);
Example
#include <iostream>
#include <limits>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
int main()
{
boost::random::mt19937 eng = boost::random::mt19937();
boost::random::uniform_real_distribution<double> urd =
boost::random::uniform_real_distribution<double>(0,20);
std::cout.precision(std::numeric_limits<double>::digits10);
for (int i = 0; i <= 100; i++)
{
std::cout << urd(eng) << std::endl;
}
}
The default precision for std::cout is set at 6, so it should work without setting this, but...

Related

Incorrect 'for' loop results C++

I am a beginner at using C++ so I was wondering if someone would be able to help me out as I'm currently trying to print a 'for' loop. The 'alfa' loop is printing correctly but when that information is called upon by the 'sina' loop, only zeros are being printed in the console.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <new>
#include <ctime>
#include <string>
#include <sstream>
#include <vector>
const double convToRad = pi/180.0;
int main(){
int INDEX = 91;
double alfa[INDEX] {0};
double sina[INDEX] {0};
for (int p = 90; p >= 0; p--){
alfa[INDEX] = p*convToRad;
//std::cout << alfa[INDEX] << std::endl;
}
for (int e = 0; e <= 90; e++){
sina[INDEX] = sin(alfa[INDEX]);
std::cout << sina[INDEX] << std::endl; //only prints 0's
}
return 0;
}
Your are accessing wrong memory location.
INDEX=91;
You had typed INDEX instead of p and e in both the loops.
So accessing a single wrong location which may gives a junk value or crash the program.
A few notes:
Don't use magical numbers, use constants.
Don't use the numbers in the array which are constant as you did.
Try a simple fix:
for (int p = 0; p < INDEX; p++) {
// storing 90* stuff in first index, 89* in second and so on...
alfa[p] = (90 - p) * convToRad;
// std::cout << alfa[p] << std::endl;
}
for (int e = 0; e < INDEX; e++) {
sina[e] = sin(alfa[e]);
std::cout << sina[e] << std::endl;
}

How can I set range to the random library

I really don't like the rand() function.I wanted to use the library but I don't really know how to set up a range for example from 1 to 3. I want to "random" these numbers(1,2,3) and not huge numbers like 243245.This code is how you can use the random library and print random numbers
#include <iostream>
#include <string>
#include <random>
using namespace std;
int main()
{
minstd_rand simple_rand;
simple_rand.seed(NULL);
for (int ii = 0; ii < 10; ++ii)
{
std::cout << simple_rand() << '\n';
}
}
Use std::uniform_int_distribution:
#include <ctime>
#include <iostream>
#include <random>
int main()
{
std::mt19937 rng(std::time(0)); // `std::minstd_rand` would also work.
std::uniform_int_distribution d(1,3);
for (int i = 0; i < 10; i++)
{
std::cout << d(rng) << '\n';
}
}
#include <iostream>
#include <random>
int main()
{
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(1, 3);
for (int n=0; n<10; ++n)
//Use dis to transform the random unsigned int generated by gen into an int in [1, 6]
std::cout << dis(gen) << ' ';
std::cout << '\n';
}
Thanks to #holyBlackCat Credit to: cppreference.com

Receiving results from a thread

I am using the following code to create 10 threads. I expect to receive different random numbers from my threads and print them. but the results are the same.
#include "pch.h"
#include <iostream>
#include "C.h"
#include "BB.h"
#include <vector>
#include <thread>
#include <mutex>
#include <future>
void initiazer(std::promise<int> * promObj, int i)
{
std::cout << "Inside Thread " <<i<< std::endl;
(promObj)->set_value((rand() % 100) + 1);
}
int main()
{
srand((unsigned)time(0));
std::promise<int> promiseObj[10];
std::future<int> futureObj [10];
std::thread th[10];
for (size_t i = 0; i < 10; i++)
{
futureObj[i] = promiseObj[i].get_future();
}
for (size_t i = 0; i < 10; i++)
{
th[i] = std::thread(initiazer,&promiseObj[i],i) ;
std::cout << futureObj[i].get() << std::endl;
}
for (size_t i = 0; i < 10; i++)
{
th[i].join();
}
return 0;
}
rand() is not threadsafe, see https://linux.die.net/man/3/rand. Use the more modern functions defined in random instead, e.g.
std::random_device rd;
auto seed = rd ();
std::mt19937 mt (seed);
....
auto random_number = mt ();
Edit:
As others have pointed out, mt19937::operator () is not guaranteed to be threadsafe either. Better then, as suggested by n.m., to create one of these objects per thread as the updated live demo now shows.
Live demo

How to include the max value of uniform_real_distribution

I am a beginner in C++ and I am trying to explore C++11 features. Here I am trying to get familiar with the new randomness generating engines.
I summarized the following code from a tutorial on this subject and I noticed two things:
1- The uniform_real_distribution doe not include the max value.
2- The commented line produce an error although it seems to work fine on the tutorial.
#include <iostream>
#include <random>
#include <chrono>
#include <string>
using namespace std;
int main(){
unsigned seed = 201;
//seed = chrono::steady_clock()::now().time_since_epoch().count();
default_random_engine e(seed);
uniform_real_distribution<double> u(0,9);
vector<double> v(10);
int num;
for(int i = 0; i < 400; ++i){
num = u(e);
++v[num];
}
for (int i = 0; i < 10; ++i)
cout << i << ": " << string(v[i],'*') << "\n";
}
I tried to find the reasons of these two things with no luck.
So, my questions:
1- How to include the max value?
2- Why I am getting the error when uncomment the chrono line ?
cannot convert 'std::chrono::_V2::steady_clock' to 'unsigned int' in initialization
Note: I am using MinGW64 g++ with c++14.
As already said by Chris Drew, you can use nextafter as the second parameter of uniform_real_distribution.
Note that you first instantiate a new object chrono::steady_clock (with chrono::steady_clock() ) and then try to call the static member now() from this object.
As now() is a static member function of chrono::steady_clock, you can (and should) directly call chrono::steady_clock::now().
Final code:
#include <iostream>
#include <random>
#include <chrono>
#include <string>
using namespace std;
int main(){
unsigned seed = 201;
seed = chrono::steady_clock::now().time_since_epoch().count();
default_random_engine e(seed);
uniform_real_distribution<double> u(0,std::nextafter(9, std::numeric_limits<double>::max()));
vector<double> v(10);
int num;
for(int i = 0; i < 400; ++i){
num = u(e);
++v[num];
}
for (int i = 0; i < 10; ++i)
cout << i << ": " << string(v[i],'*') << "\n";
}

Random number generator generating the same number even after seeding

Here's my code:
#include <iostream>
#include <string>
#include <random>
#include <ctime>
using namespace std;
int RandomIntGen(int lowerLimit, int upperLimit);
int main()
{
for (int i = 0; i < 10; i++) {
cout << "I am rolling a " << RandomIntGen(1, 6) << endl;
}
system("PAUSE");
}
// A random integer generator that takes in a upper and lower integer limit and returns a random integer
int RandomIntGen(int lowerLimit, int upperLimit) {
default_random_engine randomGenerator(time(0)); //seeding with time
uniform_int_distribution<int> randomInteger(lowerLimit, upperLimit);
return randomInteger(randomGenerator);
}
Don't know why it's generating the same value even with seeding. How do I fix this?
Moved "default_random_engine randomGenerator(time(0));" to global space to make sure it is seeded only once.
#include <iostream>
#include <string>
#include <random>
#include <ctime>
using namespace std;
//Random Generator with Seed
default_random_engine randomGenerator(time(0));
// Function Declarations
int RandomIntGen(int lowerLimit, int upperLimit);
int main()
{
for (int i = 0; i < 10; i++) {
cout << "I am rolling a " << RandomIntGen(1, 6) << endl;
}
system("PAUSE");
}
// A random integer generator that takes in a upper and lower integer limit and returns a random integer
int RandomIntGen(int lowerLimit, int upperLimit) {
uniform_int_distribution<int> randomInteger(lowerLimit, upperLimit);
return randomInteger(randomGenerator);
}