Answer the question
In order to leave comments, you need to log in
How to write a formula for the pseudo-random number generator, how to do it?
How to write a formula for rand() so that it generates, from -10.00000 to +10.00000, necessarily a fractional part and a sign? like 9.34552 or -5.35367
cheated, something like array[ i ] = ((rand() % 100000) / 100000.0) + (-10 + rand()%20) ;
Answer the question
In order to leave comments, you need to log in
#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());
Any number is easier to generate like this:
1. Create a string of the integer part of the full range from the array of 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 through the dot "." and convert the string to the number
4. Shift: subtract half of the range from the resulting range (or just randomize the sign).
rand() returns a pseudo-random number between 0 and RAND_MAX. You need -10 to +10 with a fractional part. You can do this:
Dividing by RAND_MAX, we get a float number from 0 to 1. Stretch to 20 and shift by 10.
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.6f\n", r);
}
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question