1

In c++ I wish to get a random floating point number. From what I remember the typical random number generation is done by:

rand() % 100 

which will give you values between 0 and 99

  1. What I want is rand() % PI / 12

The interpretation is a random angle between 0 and PI/12

Thanks in advance!

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216
  • 4
    NO! `rand()` is terrible, and so is modulus in combination with it! [Watch this good talk.](http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) – chris Sep 10 '13 at 01:00
  • Use [``](http://en.cppreference.com/w/cpp/numeric/random) with a uniform real distribution. – WhozCraig Sep 10 '13 at 01:04

2 Answers2

4

Using the C++11 <random> solution could look something like this:

#include <random>
#include <iostream>

int main()
{
    const int length = 60;
    std::random_device rd;
    std::mt19937_64 mt(rd());
    std::uniform_real_distribution<double> distribution(0, M_PI/12);
    for(int i = 0; i < length; i++)
    {
        double d = distribution(mt);
    std::cout << "d = " << d << std::endl;
    }
}
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
1

What you want to do is something like this:

double RealRand (double up_to)
{
    return double(rand()) / RAND_MAX * up_to;
}

Effectively, what this does is first generate a random number between 0 and 1 (left-inclusive,) and then scale the number to [0..up_to]. (Note: just in case you didn't know, rand() function generates random integers between 0 and RAND_MAX.)

However, there are (at least) two reasons you don't want to do this. First, rand() is usually a bad random number generator. And second, on some platforms (e.g. Visual C++) RAND_MAX is a very small number (32767 or something,) which leads to very poor resolution for the generated real values.

Using the facilities in <random> header (newer C++) is highly recommended.

yzt
  • 8,873
  • 1
  • 35
  • 44