How to generate random points in a circular distribution

前端 未结 6 1713
执笔经年
执笔经年 2021-02-02 17:54

I am wondering how i could generate random numbers that appear in a circular distribution.

I am able to generate random points in a rectangular distribution such that

6条回答
  •  情深已故
    2021-02-02 18:22

    import random
    import math
    
    # radius of the circle
    circle_r = 10
    # center of the circle (x, y)
    circle_x = 5
    circle_y = 7
    
    # random angle
    alpha = 2 * math.pi * random.random()
    # random radius
    r = circle_r * math.sqrt(random.random())
    # calculating coordinates
    x = r * math.cos(alpha) + circle_x
    y = r * math.sin(alpha) + circle_y
    
    print("Random point", (x, y))
    

    In your example circle_x is 500 as circle_y is. circle_r is 500.

    Another version of calculating radius to get uniformly distributed points, based on this answer

    u = random.random() + random.random()
    r = circle_r * (2 - u if u > 1 else u)
    

提交回复
热议问题