Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Producing random float from negative to positive range?

Tags:

c++

random

range

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.

like image 516
Kira Avatar asked Nov 30 '10 03:11

Kira


People also ask

How do you generate a random float number?

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.

How do you generate a random float number between a specific range in Python?

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.

How do I generate a random float number in Numpy?

Generate Random Float The random module's rand() method returns a random float between 0 and 1.

Which function is used to generate floating point random numbers?

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


4 Answers

Try this:

  1. rand() gives you a number between 0 and RAND_MAX
  2. so divide by RAND_MAX to get a number between 0 and 1
  3. you desire a range of 100 from -50 to 50, so multiply by 100.0
  4. finally shift the center from 50 (between 0 and 100 per point 3) to zero by subtracting 50.0
like image 165
Dirk Eddelbuettel Avatar answered Oct 10 '22 17:10

Dirk Eddelbuettel


Try this:

float RandomNumber(float Min, float Max)
{
    return ((float(rand()) / float(RAND_MAX)) * (Max - Min)) + Min;
}
like image 35
Maxpm Avatar answered Oct 10 '22 17:10

Maxpm


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);
like image 4
Khaled Alshaya Avatar answered Oct 10 '22 16:10

Khaled Alshaya


((float)rand())/RAND_MAX * 100.0 - 50.0
like image 4
Angus Avatar answered Oct 10 '22 16:10

Angus