c random double в диапазоне

Каким образом можно задать диапазон для Random от 0 до 0.001?

1 ответ 1

Для того чтобы получить случайное значение от 0 (включительно) до 0.001 (не включительно), можно результат вызова метода NextDouble домножить на 0.001 :

В общем случае, когда нижняя границы не равна нулю, решение выглядит так:

Имелось в виду, что нужно генерировать случайные числа на всем диапазоне ******, т.е. от -1.7*10^308 до +1.7*10^308.

А int в строчке pa=(int*)&a; тоже менять на long long ?

Смущает то, что у большинства после семнадцатой цифры идут сплошные нули

How to generate random numbers between two doubles in c++ , these numbers should look like xxxxx,yyyyy .

6 Answers 6

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).

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

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

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).

If the number of bits for the mantissa or the RNG is unknown the respective values need to be obtained within the function.

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.

Оцените статью