About Random Numbers

Very often, when modeling physical processes, it is necessary to implement a random number generator (or simply "random"). Let's start with the basics. In fact, there is no perfect, "correct" random number generator. To some extent, this task can be performed by a girl, as female logic is also a random generator (and a pretty good one). But we are interested in implementing it in QT.

The "imperfection" of randomness is that it always has a finite period, after which it repeats the same sequence. But that's not the only problem. Before using randomness, it needs to be initialized - give it a random seed, a starting point. To do this, you need to call the function void qsrand (uint seed)

This can be done in many ways, suggesting the simplest one - using the system clock.

 
#include "QTime"
QTime midnight(0,0,0);
qsrand(midnight.secsTo(QTime::currentTime()));

Now, you can use the function

 

int qrand()

- it returns a value in the range from 0 to 2147483647 (by default, this value can be changed).

The value - can be changed, but editing QT header files for this purpose is not rational. Therefore, you can use the % operation (returns the remainder of division). Like this,

 

qrand() % N

returns numbers in the range from 0 to N - 1.

Naturally, this range can be shifted into the negative region. Like this:

 

qrand() % N - K

We get numbers in the range from -K to N - K - 1

Sometimes, non-integer numbers are needed. First, from 0 to 1. For this, you can use the function:

#include "qmath.h"

double my_rand(int accuracy) { double a = 0; a = (qrand() % int (qPow(10, accuracy) + 1))/qPow(10, accuracy); return a; }

The parameter accuracy is the number of decimal places.

To obtain numbers with a fractional part in a range, simply multiply my_rand(N) by the maximum value of the range:

max*my_rand(int accuracy)

We get non-integer numbers in the range from 0 to max.

Alternatively, a simpler (and more rational) option, but you should see an alternative =)):

double QDiffusion::my_rand()
{
return (double)rand()/(RAND_MAX);
}

Returns the result with maximum precision.

I hope it's clear with decimals and expanding into the negative region.