random number between 0 and PI

Am I writing this correctly? I'm trying to get a random point on a circle by getting a random angle by getting a random number between 0 and 1 then multiplying it by 2PI.

1
2
3
  float randAngle = (rand() / RAND_MAX) * PI*2;
  float randX = cos(randAngle) * mCircleRadius;
  float randY = sin(randAngle) * mCircleRadius;
Make sure you only call srand() once at the start of your program, and then never again. Also, RAND_MAX is an integer so you have an issue with integer division (you'll always get 0).

By the way, rand() and srand() are deprecated - don't use them anymore. Instead, use the new random generators available in the <random> header:
http://www.cplusplus.com/reference/random/
http://en.cppreference.com/w/cpp/header/random
Well I fixed it with static_cast

 
  float randAngle = (static_cast <float> (rand()) / static_cast <float> (RAND_MAX)) * PI*2;


The new random generators seems complex and I don't know how to make it do what I have above, so for now I'm sticking with the old way.
No. rand() / RAND_MAX — integer division, almost always 0.

Do not use floats, unless you have a good reason to use exactly them. Native floatiing point type for C++ is double.

Prefer C++11 random facilities to C random functions (which have a great chance to be removed from C+ completely in future).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <random>

constexpr double PI = 3.14159265358;

int main()
{
    //Not the proper initialization, but will suffice for small test programms
    std::mt19937 rng( std::random_device{}() ); //Unless you are using MinGW
    std::uniform_real_distribution<> dist(0, 2*PI);
    
    //Random angle: randAngle = dist(rng) 

    std::cout.precision(2);
    std::cout.setf(std::ios::fixed);
    for(int i = 0; i < 10; ++i)
        std::cout << dist(rng) << '\n';
}
0.03
3.41
0.22
2.10
1.60
0.41
2.54
4.75
4.12
5.37
http://coliru.stacked-crooked.com/a/2fef39ba1bea00b3

Edit: damn work, distracting me in the middle of the answer.
Last edited on
Topic archived. No new replies allowed.