How to write the formula for the sensor of pseudorandom numbers, how to do it?

How to write the formula for rand() that she generated from -10.00000 to +10.00000, be sure the fractional part and the sign? view 9.34552 or -5.35367

clocked, something like array[ i ] = ((rand() % 100000) / 100000.0) + (-10 + rand()%20) ;
July 8th 19 at 12:08
4 answers
July 8th 19 at 12:10
Solution
#include <vector>
#include <random>

std::vector<double> result(100);

std::uniform_real_distribution<double> unif(-10.0, 10.0);
std::default_random_engine re;

for (int i = 0; i < 100; ++i) {
 result[i] = unif(re);
}

std::sort(result.begin(), result.end());</double></double></random></vector>
tell me now, how to sort, sorted using qsort, you get a bunch of errors - jena commented on July 8th 19 at 12:13
July 8th 19 at 12:12
Solution
From rand() range from 0 to 32767, so
((rand() % 100000) / 100000.0) // not an option
int d = rand() << 2; // this is to 131068
d += rand();
d = d % 100000;
float i = ((rand() % 20) + (d / 100000.0)) - 10.0;
32767 is the minimum. There may be more. - jena commented on July 8th 19 at 12:15
All decisions with rand() % (non-degree-2) are doomed to uneven distribution. - Delpha_Cummings commented on July 8th 19 at 12:18
July 8th 19 at 12:14
Any number of easier to generate so:
1. Create a string of the full range of the array digits [0,1,2,3,4,5,6,7,8,9].
2. Create a string of the fractional part [0,1,2,3,4,5,6,7,8,9].
3. Concatenate using the dot "." and convert the string to a number
4. Shift: subtract from the obtained the half range (or just randomin sign).
July 8th 19 at 12:16
rand() returns pseudo-random number from 0 to RAND_MAX. You have -10 to +10 with a decimal portion. You can do this:

float r = ((float)(rand()) / RAND_MAX) * 20 - 10;

Dividing by RAND_MAX, we get a float number from 0 to 1. Stretch to 20 and move on 10.

The program code with output:
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char **argv)
{
 int i, num;

 if (argc > 1)
 { 
 sscanf(argv[1], "%d", &num);
 } 
else
 { 
 num = 0;
 } 

 for (i = 0; i < num; i++)
 { 
 float r;

 r = ((float)(rand()) / RAND_MAX) * 20 - 10; 

 printf("%3.6 f\n", r); 
 } 

 return 0;
}</stdio.h></stdlib.h>

Find more questions by tags C++C