Generate a random point within a circle (uniformly)

前端 未结 21 2732
逝去的感伤
逝去的感伤 2020-11-22 15:45

I need to generate a uniformly random point within a circle of radius R.

I realize that by just picking a uniformly random angle in the interval [0 ... 2π),

21条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 16:25

    A programmer solution:

    • Create a bit map (a matrix of boolean values). It can be as large as you want.
    • Draw a circle in that bit map.
    • Create a lookup table of the circle's points.
    • Choose a random index in this lookup table.
    const int RADIUS = 64;
    const int MATRIX_SIZE = RADIUS * 2;
    
    bool matrix[MATRIX_SIZE][MATRIX_SIZE] = {0};
    
    struct Point { int x; int y; };
    
    Point lookupTable[MATRIX_SIZE * MATRIX_SIZE];
    
    void init()
    {
      int numberOfOnBits = 0;
    
      for (int x = 0 ; x < MATRIX_SIZE ; ++x)
      {
        for (int y = 0 ; y < MATRIX_SIZE ; ++y)
        {
          if (x * x + y * y < RADIUS * RADIUS) 
          {
            matrix[x][y] = true;
    
            loopUpTable[numberOfOnBits].x = x;
            loopUpTable[numberOfOnBits].y = y;
    
            ++numberOfOnBits;
    
          } // if
        } // for
      } // for
    } // ()
    
    Point choose()
    {
      int randomIndex = randomInt(numberOfBits);
    
      return loopUpTable[randomIndex];
    } // ()
    

    The bitmap is only necessary for the explanation of the logic. This is the code without the bitmap:

    const int RADIUS = 64;
    const int MATRIX_SIZE = RADIUS * 2;
    
    struct Point { int x; int y; };
    
    Point lookupTable[MATRIX_SIZE * MATRIX_SIZE];
    
    void init()
    {
      int numberOfOnBits = 0;
    
      for (int x = 0 ; x < MATRIX_SIZE ; ++x)
      {
        for (int y = 0 ; y < MATRIX_SIZE ; ++y)
        {
          if (x * x + y * y < RADIUS * RADIUS) 
          {
            loopUpTable[numberOfOnBits].x = x;
            loopUpTable[numberOfOnBits].y = y;
    
            ++numberOfOnBits;
          } // if
        } // for
      } // for
    } // ()
    
    Point choose()
    {
      int randomIndex = randomInt(numberOfBits);
    
      return loopUpTable[randomIndex];
    } // ()
    

提交回复
热议问题