C++11 random generate_canonical

The C++11 random generate_canonical is a template function that can generates a floating point value from the random number generated by the random number generator.The floating point value generated by this function is necessary to transform the number generated by the random number generator to the value which can be delivered by the random number distribution.In short this function act as a middle man for the random number generator and the random number distribution allowing a proper mutual functioning of the two.

C++11 random generate_canonical

The declaration of the generate_canonical function is shown below.

template<class RealType, size_t bits, class URNG>
RealType generate_canonical(URNG& g);

RealType – A floating point value:float, double or long double

bits – Any integer value,but if ‘bits> numeric_limits<RealType>::digits‘ , numeric_limits<RealType>::digits value is taken instead of the ‘bits’ value.

URNG -A uniform random number generator.

Return type
RealType -A floating point type whose value is always between 0 and 1,say if ‘val’ is the returned value the relation 0 < val < 1, must hold.


Stop wasting time,earn money($$$) from your website-Join Now!

Workings of generate_canonical

Suppose ,

generate_canonical working function

R=g.max()− g.min() + 1

Now invoke g()k‘(obtain from evaluating the first equation) times to get the sequence g0, g1…,gk−1.After obtaining the sequence evaluate the sequence,

generate_canonical working function

then the resultant value of S/Rk is the value returned by the generate_canonical function.

Note this function is mainly used by the compiler to help generate the correct random number from the random distribution using the engine generated value and we programmer in general has not much use for it.

A code example implementing the function is given below.The true intention of the example however is to show you how to call the function and that the return value is always more than 0 but less than 1.

Link :C++11 random linear_congruential_engine

Code example

linear_congruential_engine<unsigned int , 23 , 0 , 900 > lce ;

cout<< generate_canonical<double , 6 >( lce ) ;

cout<< generate_canonical<unsigned int , 6 >( lce ) ; //error,the first parameter type must be floating point type

Output in Code::blocks,