Xtense
Xtense

Reputation: 646

Function to generate more than one random point in a given circle

So I have defined a fucntion to generate a random number in a given circle:

def rand_gen(R,c):
    # random angle
    alpha = 2 * math.pi * random.random()
    # random radius
    r = R * math.sqrt(random.random())
    # calculating coordinates
    x = r * math.cos(alpha) + c[0]
    y = r * math.sin(alpha) + c[1]
    return (x,y)

Now I want to add a parameter n (rand_gen(R,c,n)) such that we can get n such numbers instead of one

Upvotes: 1

Views: 119

Answers (2)

xana
xana

Reputation: 499

You can achieve that goal also using generator function:

import random
import math

def rand_gen(R,c,n):
    while n:
      # random angle
      alpha = 2 * math.pi * random.random()
      # random radius
      r = R * math.sqrt(random.random())
      # calculating coordinates
      x = r * math.cos(alpha) + c[0]
      y = r * math.sin(alpha) + c[1]
      n -= 1
      yield (x,y)

points_gen = rand_gen(10, (3,4), 4)
for point in points_gen:
  print(point)

points = [*rand_gen(10, (3,4), 4)]
print(points)

Upvotes: 3

Andrej Kesely
Andrej Kesely

Reputation: 195418

If you want to generate n random points, you can extend your function with a parameter and for-loop:

import math
import random

def rand_gen(R, c, n):
    out = []
    for i in range(n):
        # random angle
        alpha = 2 * math.pi * random.random()
        # random radius
        r = R * math.sqrt(random.random())
        # calculating coordinates
        x = r * math.cos(alpha) + c[0]
        y = r * math.sin(alpha) + c[1]
        out.append((x,y))
    return out

print(rand_gen(10, (3, 4), 3))

Prints (for example):

[(-4.700562169626218, 5.62666979720004), (6.481518730246707, -1.849892172014873), (0.41713910134636345, -1.9065302305716285)]

But better approach in my opinion would be leave the function as is and generate n points using list comprehension:

lst = [rand_gen(10, (3, 4)) for _ in range(3)]
print(lst)

Prints:

[(-1.891474340814674, -2.922205399732765), (12.557063558442614, 1.9323688240857821), (-5.450160078420653, 7.974550456763403)]

Upvotes: 3

Related Questions