c++ - How to fill an array with random floating point numbers? -
i'm hoping find way fill array random floating point numbers. array size 50 , i'm hoping fill array random float numbers range 1-25. here have far. appreciate tips or answers can offer. thank you.
#include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main() { float myarray[50]; for(int = 1; <= 25; i++) { srand(time(0)); myarray[i] = (rand()% 50 + 1); cout << myarray[i] << endl; system("pause"); return 0; } }
if c++11 not option, can use rand
, dividing result rand_max
constant casted float
obtain uniform distribution of floats in range [0, 1]; can multiply 24 , add 1 desired range:
myarray[i] = rand()/float(rand_max)*24.f+1.f;
by way, other observed, move srand
out of loop - rng seed (normally) must initialized once.
(notice dividing rand_max
give distribution includes right extreme of interval; if want exclude it, should divide e.g. rand_max+1
)
of course, resulting distribution original rand()
distribution (both in randomness , in granularity); typically lcg , granularity of @ least ~0.0007 (guaranteed standard, , vc++ , other compilers provide). if need better random numbers, should follow advices posted in other answers (the default mersenne twister generator in c++11 provides better randomness , way bigger guaranteed range).
Comments
Post a Comment