As stated above there are multiple methods. My first thought is also calsign's solution. I think/guess this solution is frequently used. I wanted to test two methods against each other with regard to speed, since both have costly features:
[Rect Method] Generating random points within the rect and discarding those outside the radius is computationally less costly, however you will have to generate more points to get the same amount (because some are discarded).
[Angle Method] Calculating it directly with math ensures doing the calculations once but there are costly calculation in there like sqrt, cos and sin.
I've created two small tests. Please comment if something is wrong with these. Both are able to generate random points within a circle very fast and can be used by the OP. But with regard to speed it seems that in Processing the
Angle Method is faster.
Rect Method Test
- // takes about 515.000 nanoseconds to generate 5000 points
- int radius = 200;
- void setup() {
- for (int j=0; j<50; j++) {
- long now = System.nanoTime();
- for (int i=0; i<5000; i++) {
- float x = random(-radius, radius);
- float y = random(-radius, radius);
- while (dist(x,y,0,0) > radius) {
- x = random(-radius, radius);
- y = random(-radius, radius);
- }
- }
- long delta = System.nanoTime()-now;
- println(nf(j,2) + "|" + delta);
- }
- exit();
- }
Angle Method Test
- // takes about 332.000 nanoseconds to generate 5000 points
- int radius = 200;
- void setup() {
- for (int j=0; j<50; j++) {
- long now = System.nanoTime();
- for (int i=0; i<5000; i++) {
- float q = random(1) * (TWO_PI);
- float r = sqrt(random(1));
- float x = (radius * r) * cos(q);
- float y = (radius * r) * sin(q);
- }
- long delta = System.nanoTime()-now;
- println(nf(j,2) + "|" + delta);
- }
- exit();
- }