I am trying to produce a random float within the range -50.0 and 50.0 inclusively, using rand(). I've looked everywhere for an answer but it deals with ints and % operator.
In order to generate Random float type numbers in Java, we use the nextFloat() method of the java. util. Random class. This returns the next random float value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence.
The random. uniform() function returns a random floating-point number between a given range in Python. For example, It can generate a random float number between 10 to 100 Or from 50.50 to 75.5.
Generate Random Float The random module's rand() method returns a random float between 0 and 1.
We can generate float random numbers by casting the return value of the rand () function to 'float'. Thus the following will generate a random number between float 0.0 and 1.0 (both inclusive).
Try this:
rand()
gives you a number between 0 and RAND_MAX
RAND_MAX
to get a number between 0 and 1Try this:
float RandomNumber(float Min, float Max)
{
return ((float(rand()) / float(RAND_MAX)) * (Max - Min)) + Min;
}
Honestly, all present answers don't explain that there is a change in distribution in their solutions(I am assuming that rand() follows the uniform distribution! correct me if I am wrong please). Use a library please, and my recommendation is using the new facilities in C++0x:
#include <random>
#include <functional>
int main()
{
std::mt19937 generator;
std::uniform_real_distribution<float> uniform_distribution(-50.0, 50.0);
auto my_rand = std::bind(uniform_distribution, generator);
}
If you can't, Boost is a perfect choice. That way, you can use my_rand() just like good ol' rand():
std::vector<float> random_numbers(1000);
std::generate(random_numbers.begin(), random_numbers.end(), my_rand);
((float)rand())/RAND_MAX * 100.0 - 50.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With