rand() or qrand() functions generate a random int.
int a= rand();
I want to get an random number between 0 and 1.
How I can do this Work?
You can generate a random int into a float, and then divide it by RAND_MAX, like this:
float a = rand(); // you can use qrand here
a /= RAND_MAX;
The result will be in the range from zero to one, inclusive.
Using C++11 you can do the following:
Include the random header:
#include<random>
Define the PRNG and the distribution:
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0,1.0);
Get the random number
double number = distribution(generator);
In this page and in this page you can find some references about uniform_real_distribution.
Check this post, it shows how to use qrand for your purpose which is afaik a threadsafe wrapper around rand().
#include <QGlobal.h>
#include <QTime>
int QMyClass::randInt(int low, int high)
{
// Random number between low and high
return qrand() % ((high + 1) - low) + low;
}
#include <iostream>
#include <ctime>
using namespace std;
//
// Generate a random number between 0 and 1
// return a uniform number in [0,1].
inline double unifRand()
{
return rand() / double(RAND_MAX);
}
// Reset the random number generator with the system clock.
inline void seed()
{
srand(time(0));
}
int main()
{
seed();
for (int i = 0; i < 20; ++i)
{
cout << unifRand() << endl;
}
return 0;
}
Take a module from the random number which will define the precision. Then do a typecast to float and divide by the module.
float randNum(){
int random = rand() % 1000;
float result = ((float) random) / 1000;
return result;
}
Related
float genData(int low, int high);
int main(){
srand(time(0));
float num = genData(40, 100);
cout << fixed << left << setprecision(2) << num << endl;
return 0;
}
float genData(int low, int high) {
low *= 100;
high *= 100 + 1;
int rnd = rand() % (high - low) + low;
float newRand;
newRand = (float) rnd / 100;
return newRand;
}
I'm expecting a random number between 40 and 100 inclusively with two decimal places.
eg: 69.69, 42.00
What I get is the same number with different decimal values, slowly increasing every time I run the program.
Use the <random> header for that:
#include <iostream>
#include <random>
float getData(int const low, int const high) {
thread_local auto engine = std::mt19937{ std::random_device{}() };
auto dist = std::uniform_int_distribution<int>{ low * 100, high * 100 };
return dist(engine) / 100.0f;
}
int main() {
for (auto i = 0; i != 5; ++i) {
std::cout << getData(40, 100) << '\n';
}
}
Wrong range
int rnd = rand() % (high - low) + low; does not generate the right range.
float genData(int low, int high) {
low *= 100;
// high *= 100 + 1;
high = high*100 + 1;
expecting a random number between 40 and 100 inclusively with two decimal places. eg: 69.69, 42.00
That is [40.00 ... 100.00] or 10000-4000+1 different values
int rnd = rand() % (100*(high - low) + 1) + low*100;
float frnd = rnd/100.0f;
rand() weak here when RAND_MAX is small
With RAND_MAX == 32767, int rnd = rand() % (high - low) + low; is like [0... 32767] % 6001 + 40000. [0... 32767] % 6001 does not provide a very uniform distribution. Some values coming up 6 times and others 7-ish.
If you are using C++ 11 you can use better random number generators that will give you diversity in the generated numbers in addition to being a lot faster.
Quick Example:
#include <random> // The header for the generators.
#include <ctime> // To seed the generator.
// Generating random numbers with C++11's random requires an engine and a distribution.
mt19937_64 rng(seed);
// For instance, we will create a uniform distribution for integers in the (low, high) range:
uniform_int_distribution<int> unii(low, high);
// Show the random number
cout << unii(rng) << ' ';
You can follow this article for more explanation from here.
So ive made a MAC Address generator. But the random part is very strange. It randomly generates a number that i use to choose something from an array. But each time you run the exe. It gens the same number.
Here is my code
#include <random>
#include <string>
//Mac Addr example -> 82-F5-4D-72-C1-EA
//6 two char sets
//Dont include spaces/dashes/dots
std::string chars[] = { "A","B","C","D","E","F" };
int nums[] = { 0,1,2,3,4,5,6,7,8,9 };
std::string GenMacAddr()
{
std::string final;
std::string CharSet;
int choice;
for (int i = 0; i < 6; i++) {
choice = 1 + rand() % 4;
if (choice == 1) { //Char Set only int
for (int x = 0; x < 2; x++) { //Makes action happen twice
final += std::to_string(nums[rand()%10]);
}
}
else if (choice == 2) { //Char set only str
for (int x = 0; x < 2; x++) { //Makes action happen twice
final += chars[rand() % 6];
}
}
else if (choice == 3) {
final += chars[rand() % 6];
final += std::to_string(nums[rand() % 10]);
}
else if (choice == 4) {
final += std::to_string(nums[rand() % 10]);
final += chars[rand() % 6] ;
}
}
return final;
}
rand() is a deterministic random number generator . In order to achieve actual pseudo-random results you should first seed it with something like srand(time(NULL)) .
If you look around this you will realize that this is a bad approach and you should instead give up rand() altogether , instead use <random> from C++11 . Stephan T. Lavavej has a really nice talk about it , you should see it here .
Here is also the code snippet he recommends from that talk .
#include <random>
#include <iostream>
int main() {
std::random_device random_dev; // (Non?) deterministic random number generator
std::mt19937 mers_t(random_dev()); // Seed mersenne twister with it .
std::uniform_int_distribution<int> distribution(0, 100); // Bound the output.
// Print a random integer in the range [0,100] ( included ) .
std::cout << distribution(mers_t) << '\n';
}
EDIT:
As François noted, std::random_device isn't required to be non-deterministic and it's actually implementation dependent.
One indication to tell if it is or not is by checking the value of entropy() method call but then again some implementations return just a fixed value. In that case you might consider using std::chrono to generate a seed the way Ted describes.
rand() is a pseudo random number generator. It will generate numbers according to an algorithm designed to have a long period (before it starts repeating itself) - but it needs a starting point. This is called the seed. You seed rand() with the srand() function and you should only seed it once during the program's execution. Seeding is often done with time but since time commonly returns whole seconds (since the epoch) you risk using the same seed if you start the program more than once (within a second).
You could instead use std::random_device to generate the seed if it has entropy and use a time based seed only as a fallback.
Example:
#include <cstdlib>
#include <chrono>
#include <iostream>
#include <random>
#include <string>
#include <type_traits>
unsigned seed() { // a function to generate a seed
std::random_device rd;
if(rd.entropy() > 0.) return rd(); // if random_device has entropy, use it
// fallback, use duration since the epoch
auto dse = (std::chrono::steady_clock::now() -
std::chrono::steady_clock::time_point{}).count();
return static_cast<std::make_unsigned_t<decltype(dse)>>(dse);
}
std::string GenMacAddr() {
static const char chars[] = {'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F'};
std::string result(6 * 2, ' ');
for(char& ch : result) ch = chars[std::rand() % std::size(chars)];
return result;
}
int main() {
std::srand(seed()); // seed rand()
// generate 10 mac addresses
for(int i = 0; i < 10; ++i) std::cout << GenMacAddr() << '\n';
}
That said, you could use one of the more modern pseudo random number generators, like std::mt19937, instead of rand() and use std::uniform_int_distribution instead of the modulus operation:
template<class PRNG = std::mt19937>
auto& prng() {
// same seed() function as in the previous example:
thread_local PRNG prng_instance(seed());
return prng_instance;
}
std::string GenMacAddr() {
static const char chars[] = {'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F'};
thread_local std::uniform_int_distribution<unsigned> dist(0, std::size(chars) - 1);
std::string result(6 * 2, ' ');
for(char& ch : result) ch = chars[dist(prng())];
return result;
}
I want to generate (pseudo) random numbers between 0 and some integer. I don't mind if they aren't too random. I have access to the current time of the day but not the rand function. Can anyone think of a sufficiently robust way to generate these? Perhaps, discarding some bits from time of day and taking modulo my integer or something?
I am using c.
If you're after an ultra-simple pseudo-random generator, you can just use a Linear Feedback shift Register.
The wikipedia article has some code snippets for you to look at, but basically the code for a 16-bit generator will look something like this (lightly massaged from that page...)
unsigned short lfsr = 0xACE1u;
unsigned bit;
unsigned rand()
{
bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
return lfsr = (lfsr >> 1) | (bit << 15);
}
For "not too random" integers, you could start with the current UNIX time, then use the recursive formula r = ((r * 7621) + 1) % 32768;. The nth random integer between 0 (inclusive) and M (exclusive) would be r % M after the nth iteration.
This is called a linear congruential generator.
The recursion formula is what bzip2 uses to select the pivot in its quicksort implementation. I wouldn't know about other purposes, but it works pretty well for this particular one...
Look at implementing a pseudo-random generator (what's "inside" rand()) of your own, for instance the Mersenne twister is highly-regarded.
#include <chrono>
int get_rand(int lo, int hi) {
auto moment = std::chrono::steady_clock::now().time_since_epoch().count();
int num = moment % (hi - lo + 1);
return num + lo;
}
The only "robust" (not easily predictable) way of doing this is writing your own pseudo-random number generator and seeding it with the current time. Obligatory wikipedia link: http://en.wikipedia.org/wiki/Pseudorandom_number_generator
You can get the "Tiny Mersenne Twister" here: http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/TINYMT/index.html
it is pure c and simple to use. E.g. just using time:
#include "tinymt32.h"
// And if you can't link:
#include "tinymt32.c"
#include <time.h>
#include <stdio.h>
int main(int argc, const char* argv[])
{
tinymt32_t state;
uint32_t seed = time(0);
tinymt32_init(&state, seed);
for (int i=0; i<10; i++)
printf("random number %d: %u\n", i, (unsigned int)tinymt32_generate_uint32(&state));
}
The smallest and simple random generator which work with ranges is provided below with fully working example.
unsigned int MyRand(unsigned int start_range,unsigned int end_range)
{
static unsigned int rand = 0xACE1U; /* Any nonzero start state will work. */
/*check for valid range.*/
if(start_range == end_range) {
return start_range;
}
/*get the random in end-range.*/
rand += 0x3AD;
rand %= end_range;
/*get the random in start-range.*/
while(rand < start_range){
rand = rand + end_range - start_range;
}
return rand;
}
int main(void)
{
int i;
for (i = 0; i < 0xFF; i++)
{
printf("%u\t",MyRand(10,20));
}
return 0;
}
If you're not generating your numbers too fast (*1) and your upper limit is low enough (*2) and your "time of day" includes nanoseconds, just use those nanoseconds.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int nanorand(void) {
struct timespec p[1];
clock_gettime(CLOCK_MONOTONIC, p);
return p->tv_nsec % 1000;
}
int main(void) {
int r, x;
for (;;) {
r = nanorand();
do {
printf("please type %d (< 50 quits): ", r);
fflush(stdout);
if (scanf("%d", &x) != 1) exit(EXIT_FAILURE);
} while (x != r);
if (r < 50) break;
}
puts("");
return 0;
}
And a sample run ...
please type 769 (< 50 quits): 769
please type 185 (< 50 quits): 185
please type 44 (< 50 quits): 44
(*1) if you're using them interactively, one at a time
(*2) if you want numbers up to about 1000
You can write your own rand() function. Like:
Method 1: Using the Concept of static variable:
example code:
int random_number_gen(int min_range, int max_range){
static int rand_number = 199198; // any random number
rand_number = ((rand_number * rand_number) / 10 ) % 9890;
return rand_number % (max_range+1-min_range) + min_range ;
}
Method 2. Using a random/unique value, for example, the current time in microseconds.
#include<time.h>
#include <chrono>
using namespace std;
uint64_t timeSinceEpochMicrosec() {
using namespace std::chrono;
return duration_cast<microseconds>(system_clock::now().time_since_epoch()).count();
}
int random_number_gen(int min_range, int max_range){
long long int current_time = timeSinceEpochMicrosec();
int current_time_in_sec = current_time % 10000000;
int rand_number = current_time_in_sec % (max_range+1-min_range) + min_range ;
return rand_number;
}
import java.io.*;
public class random{
public static class p{
}
static long reg=0;
static long lfsr()
{
if(reg==0)
{
reg=145896027340307l;
}
long bit=(reg>>0^reg>>2^reg>>3^reg>>5)&1;
reg=reg>>1|bit<<62;
return reg;
}
static long getRand()
{
String s=String.valueOf(new p());
//System.out.println(s);
long n=0;
lfsr();
for(int i=0;i<s.length();i++)
{
n=n<<8|+s.charAt(i);
}
System.out.print(n+" "+System.currentTimeMillis()+" "+reg+" ");
n=n^System.currentTimeMillis()^reg;
return n;
}
public static void main(String args[])throws IOException
{
for(int i=0;i<400;i++)
{
System.out.println(getRand());
}
}
}
This is a random number generator where it is guaranteed that the sequence never repeats itself. I have paired time with object value (randomly put by java) with LFSR.
Advantages:
The sequence doesn't repeat itself
The sequence is new on every run
Disadvantages:
Only compatible with java. In C++, new object that is created is same on every run.
But there too time and LFSR parameters would put in enough randomness
It is slower than most PRNGs as an object needs to be created everytime a number is needed
#include<time.h>
int main(){
int num;
time_t sec;
sec=time(NULL);
printf("Enter the Range under which you want Random number:\n");
scanf("%d",&num);
if(num>0)
{
for(;;)
{
sec=sec%3600;
if(num>=sec)
{
printf("%ld\n",sec);
break;
}
sec=sec%num;
}
}
else
{
printf("Please Enter Positive Value!\n");
}
return 0;
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
unsigned int x,r,i;
// no of random no you want to generate
scanf("%d",&x);
// put the range of random no
scanf("%d",&r);
unsigned int *a=(unsigned int*)malloc(sizeof(unsigned int)*x);
for(i=0;i<x;i++)
printf("%d ",(a[i]%r)+1);
free(a);
getch();
return 0;
}
One of the simplest random number generator which not return allways the same value:
uint16_t simpleRand(void)
{
static uint16_t r = 5531; //dont realy care about start value
r+=941; //this value must be relative prime to 2^16, so we use all values
return r;
}
You can maybe get the time to set the start value if you dont want that the sequence starts always with the same value.
I'm having some trouble generating a random double number. I have to create a function that takes no arguments and returns a double (between 0 and 100), the random number. Expect every time I try to create it, it returns a value of 1.
I also have to use a few symbolic constants.
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
double randDouble();
const double UPPER_BOUND = 100.0;
const double LOWER_BOUND = 0.0;
const int ARRAY_SIZE = 100;
double randDouble()
{
int randomInt;
double randomDouble;
srand(time(NULL));
randomInt = rand() % 100 + 1;
randomDouble = LOWER_BOUND + (randomInt / RAND_MAX / ( UPPER_BOUND - LOWER_BOUND));
return randomDouble;
}
int main()
{
cout << randDouble();
return 0;
}
Another thing is, I have to use a pre-given formula for it.
lower bound + ( random integer / (maximum possible random number / (upper bound - lower bound))
First of all, you are not calling randDouble in your main, but try to print the function itself. This will always print 1 or true, depending on whether boolalpha is set. Your compiler would have warned you about that if you had enabled a more aggressive warning level. This is generally recommended.
When you fix this, you will notice that you always get zero. This is because randomInt / RAND_MAX is always zero because of truncating integer division.
When you fix that, you will notice that the returned values are not as desired because your formula is incorrect.
A lot of such problems can be avoided by using the modern std::uniform_real_distribution which already does all the hard work for you.
You can do it in a better and a cleaner way:
#include<random>
#include<iostream>
using namespace std;
int main(){
std::random_device rand_dev;
std::mt19937 gen(rand_dev());
std::uniform_real_distribution<double> dist(0, 100);
// demo.
for(int i = 0; i < 100; ++i){
// call dist(gen) whenever you need a random variable.
cout << dist(gen) << '\n';
}
return 0;
}
This code uses C++11 and won't work on earlier versions.
How to generate random numbers between two doubles in c++ , these numbers should look like xxxxx,yyyyy .
Here's how
double fRand(double fMin, double fMax)
{
double f = (double)rand() / RAND_MAX;
return fMin + f * (fMax - fMin);
}
Remember to call srand() with a proper seed each time your program starts.
[Edit]
This answer is obsolete since C++ got it's native non-C based random library (see Alessandro Jacopsons answer)
But, this still applies to C
This solution requires C++11 (or TR1).
#include <random>
int main()
{
double lower_bound = 0;
double upper_bound = 10000;
std::uniform_real_distribution<double> unif(lower_bound,upper_bound);
std::default_random_engine re;
double a_random_double = unif(re);
return 0;
}
For more details see John D. Cook's "Random number generation using C++ TR1".
See also Stroustrup's "Random number generation".
This should be performant, thread-safe and flexible enough for many uses:
#include <random>
#include <iostream>
template<typename Numeric, typename Generator = std::mt19937>
Numeric random(Numeric from, Numeric to)
{
thread_local static Generator gen(std::random_device{}());
using dist_type = typename std::conditional
<
std::is_integral<Numeric>::value
, std::uniform_int_distribution<Numeric>
, std::uniform_real_distribution<Numeric>
>::type;
thread_local static dist_type dist;
return dist(gen, typename dist_type::param_type{from, to});
}
int main(int, char*[])
{
for(auto i = 0U; i < 20; ++i)
std::cout << random<double>(0.0, 0.3) << '\n';
}
If accuracy is an issue here you can create random numbers with a finer graduation by randomizing the significant bits.
Let's assume we want to have a double between 0.0 and 1000.0.
On MSVC (12 / Win32) RAND_MAX is 32767 for example.
If you use the common rand()/RAND_MAX scheme your gaps will be as large as
1.0 / 32767.0 * ( 1000.0 - 0.0) = 0.0305 ...
In case of IEE 754 double variables (53 significant bits) and 53 bit randomization the smallest possible randomization gap for the 0 to 1000 problem will be
2^-53 * (1000.0 - 0.0) = 1.110e-13
and therefore significantly lower.
The downside is that 4 rand() calls will be needed to obtain the randomized integral number (assuming a 15 bit RNG).
double random_range (double const range_min, double const range_max)
{
static unsigned long long const mant_mask53(9007199254740991);
static double const i_to_d53(1.0/9007199254740992.0);
unsigned long long const r( (unsigned long long(rand()) | (unsigned long long(rand()) << 15) | (unsigned long long(rand()) << 30) | (unsigned long long(rand()) << 45)) & mant_mask53 );
return range_min + i_to_d53*double(r)*(range_max-range_min);
}
If the number of bits for the mantissa or the RNG is unknown the respective values need to be obtained within the function.
#include <limits>
using namespace std;
double random_range_p (double const range_min, double const range_max)
{
static unsigned long long const num_mant_bits(numeric_limits<double>::digits), ll_one(1),
mant_limit(ll_one << num_mant_bits);
static double const i_to_d(1.0/double(mant_limit));
static size_t num_rand_calls, rng_bits;
if (num_rand_calls == 0 || rng_bits == 0)
{
size_t const rand_max(RAND_MAX), one(1);
while (rand_max > (one << rng_bits))
{
++rng_bits;
}
num_rand_calls = size_t(ceil(double(num_mant_bits)/double(rng_bits)));
}
unsigned long long r(0);
for (size_t i=0; i<num_rand_calls; ++i)
{
r |= (unsigned long long(rand()) << (i*rng_bits));
}
r = r & (mant_limit-ll_one);
return range_min + i_to_d*double(r)*(range_max-range_min);
}
Note: I don't know whether the number of bits for unsigned long long (64 bit) is greater than the number of double mantissa bits (53 bit for IEE 754) on all platforms or not.
It would probably be "smart" to include a check like if (sizeof(unsigned long long)*8 > num_mant_bits) ... if this is not the case.
This snippet is straight from Stroustrup's The C++ Programming Language (4th Edition), §40.7; it requires C++11:
#include <functional>
#include <random>
class Rand_double
{
public:
Rand_double(double low, double high)
:r(std::bind(std::uniform_real_distribution<>(low,high),std::default_random_engine())){}
double operator()(){ return r(); }
private:
std::function<double()> r;
};
#include <iostream>
int main() {
// create the random number generator:
Rand_double rd{0,0.5};
// print 10 random number between 0 and 0.5
for (int i=0;i<10;++i){
std::cout << rd() << ' ';
}
return 0;
}
For generating random numbers we can use the methods that our other friends told. I want to add a very important point here.
The code told by others is :
//I have made this as a function that returns the random double value, just copy this
// if you want
double random(){
return (double)rand() / RAND_MAX; // for generating random points between 0 to 1
}
//now suppose I want any random value between two numbers min and max then I can use this as :
int mynum = min + (max-min)*random();
But the problem with this code is that it is biased, I mean that it is not giving value equally between 0 and 1.
Click here to see the image This image shows how the value returned is more biased towards the center (i.e. is near value one). In order to avoid such condition we should prefer the following code:
double random(){
return sqrt((double)rand() / RAND_MAX); // for generating random points between 0 to 1
}
Reason for choosing Square root function
The reason for choosing sqrt() rather than any other functions like cbrt() to bias it towards the outer end is that in the first approach mentioned above, the points generated were proportional to R^2 because our random was proportional to R, thus making points overall area of the circle proportional to R^2 which made them concentrated more towards the center. Making our random proportional to sqrt(R) would make the points generated over all the area of the circle proportional to R which would make all the points generate uniformly throughout the circle.
Note that after applying sqrt (a point between [0, 1]), the result would be a value greater than the original random() thus making it biased more towards the outer end. This makes the point uniformly generated over all of the circle.
I would like to thank #archit91 for sharing this usefull information on LeetCode in this article
So many great solutions already and many are very elegant. I just figured I would add another to the list. I am drawing references directly from the 'Modern C++ Programming CookBook, 2nd edition'. In the chapter on random number generators, there is some emphasis on how very important it is to properly initialize the pseudo-random number generators. It adds that the Mersenne twister engine has a bias towards producing some values repeatedly and not including other values therefore not generating numbers in a uniform distribution but more like a binomial or Poisson distribution. The snippet I am including goes through the steps of initializing a generator in order to produce pseudo-random numbers with a true uniform distribution.
auto generate_random_double(double lb, double ub)//lb= lowerbound, ub = upperbound
{
//produce random #'s to be used as seeding values
std::random_device rd{};
//Generate random data for all the internal bits of the engine
std::array<double, std::mt19937::state_size> seed_data{};
ranges::generate(seed_data,std::ref(rd));
//Create an std::seed_seq object from the pseudo random data
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
//Create an engine object and initialize the bits representing the internal
//state of the engine; form example an mt19937 has 19937 bits
auto eng = std::mt19937{ seq };
//Create object based on the approprieat distribution based on application
//requirments
const auto randDouble = std::uniform_real_distribution<>{ lb,ub };
//return object seeded with the previously initialized object
return randDouble(eng);
}//end method generate_random_double
Here's a self-contained C++ class using C++11. It generates a random double within a half-open interval [low, high) (low <= x < high).
#include <random>
// Returns random double in half-open range [low, high).
class UniformRandomDouble
{
std::random_device _rd{};
std::mt19937 _gen{_rd()};
std::uniform_real_distribution<double> _dist;
public:
UniformRandomDouble() {
set(1.0, 10.0);
}
UniformRandomDouble(double low, double high) {
set(low, high);
}
// Update the distribution parameters for half-open range [low, high).
void set(double low, double high) {
std::uniform_real_distribution<double>::param_type param(low, high);
_dist.param(param);
}
double get() {
return _dist(_gen);
}
};
This is similar to my answer above but should work from C++11 and up.
#include <iostream>
#include <random>
#include <array>
#include <algorithm>
#include <functional>
/**
* a function that will generate pseudo random numbers in a normal distribution
* #param lb is the lower bound of the distribution (inclusive)
* #param ub is the upper bound of the distribution (inclusive)
* #return a pseudo random number in the range [lb, ub]
*/
auto generate_random_double(double lb, double ub)
{
std::random_device rd{};
std::array<double, std::mt19937::state_size> seed_data{};
std::generate(seed_data.begin(), seed_data.end(), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
auto eng = std::mt19937{ seq };
const auto randDouble = std::uniform_real_distribution<>{ lb,ub };
return std::bind(randDouble, eng);
}
something like this:
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
const long max_rand = 1000000L;
double x1 = 12.33, x2 = 34.123, x;
srandom(time(NULL));
x = x1 + ( x2 - x1) * (random() % max_rand) / max_rand;
cout << x1 << " <= " << x << " <= " << x2 << endl;
return 0;
}