## how to generate a set of random points within a half-circle uniformly in python or R?

generate random points in a circle python

random point in circle

randomly pick a point on a unit disk

I am trying to generate a set of points within a half-circle uniformly.

size = 1000 t = np.random.random(size)*np.pi*2 u = np.random.random(size) + np.random.random(size) r = np.where(u > 1, 2 - u, u) x = r*cos(t) y = r*sin(t) coor = (x,y) for idx, value in enumerate(y): if value<0: x[idx]=-3 y[idx]=-3 f, ax = plt.subplots(figsize = (3,3)) plt.scatter(x, y)

this piece of code has 2 bugs.

- the plot has a lot (-3,-3) points to be removed
- it seems to be inefficient.

the figure shown as below is NOT uniformly, as the points are more of center than others.

another plot shown as below could be viewed as uniformly.

any idea to fix the bugs would be appreciated.

In R:

runif_in_semicircle <- function(n, radius=1){ theta <- runif(n, 0, pi) r <- radius * sqrt(runif(n)) cbind(r*cos(theta), r*sin(theta)) } sims <- runif_in_semicircle(1000) plot(sims[,1], sims[,2], asp=1, pch=19)

We can check it works by evaluating an integral.

# integrand example f <- function(x) x[1]^2 + exp(x[2]) set.seed(666) sims <- runif_in_semicircle(10000) fsims <- apply(sims, 1, f) mean(fsims)*pi/2 # approximates the integral of f over the half-disk # 2.890905

Now we numerically evaluate the integral of `f`

.

library(SphericalCubature) adaptIntegrateBallPolar(f, n=2, lowerLimit = 0, upperLimit = pi) # $integral # [1] 2.880598

**How to generate uniform random points with in a circle.,** I used "rand" function to generate uniform random points within the circle, but y = y0 + r.*sin(t);. % Now display our random set of points in a figure. plot(x,y, 'o',� Use randint () when you want to generate a random number from an inclusive range. Use randrange () when you want to generate a random number within a range by specifying step value. It produces a random number from an exclusive range. You should be aware of some value constraints of a randrange () function.

You should generate uniformly distributed angles `phi`

, and take the `sqrt`

of uniformly generated radius `r`

(which takes into account that we want to sample uniformly on the *area*, see explanation below), to make sure you sample points uniformly in the half-circle.

import numpy as np import matplotlib.pyplot as plt # sample size = 10000 R = 1 phi = np.random.random(size=size) * np.pi r = np.sqrt(np.random.random(size=size)) * R # transform x = r * np.cos(phi) y = r * np.sin(phi) # plot f = plt.figure(figsize=(12,12)) a = f.add_subplot(111) a.scatter(x, y, marker='.') a.set_aspect('equal') plt.show()

##### Explanation

To generate uniformly distributed points on a (half-)circle we have to make sure that each infinitesimal *area* or segment is "hit" with the same probability. We can simply sample `phi`

from a uniform random distribution `[0, 1)`

, multiplied by `np.pi`

(so `[0, pi)`

), since all angles should have the same probability to be sampled. But if we sample `r`

from a uniform random distribution in `[0, 1)`

, we generate too many points at small radia, and not enough at large radia, since the *area* grows like `r**2`

. To take that fact into account, we have to bias our sampled radia accordingly, and in this case we can apply the biasing by simply taking the square root (`np.sqrt`

), to apply the correct weighting to the sampled radius values, and take into account the larger area of the outer rings.

A much better and more thorough explanation is found here: https://stackoverflow.com/a/50746409/1170207

##### Performance comparison to rejection sampling methods

Since this method is basically an inversion sampling method, we compare its performance to a rejection sampling algorithm.

import numpy as np x, y = np.random.random(size=(2,10000)) %timeit r, phi = np.sqrt(x), y # 19 µs ± 33.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %timeit m = x**2 + y**2 <= 1; xx, yy = x[m], y[m] # 81.5 µs ± 271 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

With the rejection sampling method we also cannot ensure that we draw a select number of variates, so we have to repeat the process until we have. This cannot be vectorized that nicely, unless we accept to sample too many values, and discard additional ones.

**How to generate random points in a circular distribution,** generate random latitude/longitude within radius python Generating a random point within a circle (uniformly), For a circle of radius R, you use R*sqrt(rand())� Refer our guide to Generate the random string in Python. This guide includes the following things: – Generate random the string of fixed length. Get the random alphanumeric string with letters and digits. Generate the random password which contains the letters, digits and special symbols. Cryptographically secure random generator in Python

You should generate points in the enclosing rectangle, and remove points which are not in the half-circle

# generate about n points in a half-circle with # given center (x, y) and given radius, and y>0 points <- function(x, y, radius, n) { n2 = n * 4 / pi # each point has pi/4 probability to survive # make [-1, 1] * [-1, 1] square xs = runif(n2, -1, 1) ys = runif(n2, 0, 1) # or just runif(n2) points = cbind(xs, ys) # keep only points in circle with center (0,0) and radius 1 with y>0 ind = (xs**2 + ys**2 <= 1) # the condition ys>=0 is obeyed already points = points[ind,] # move/stretch to given center and radius points = points * radius points[,1] = points[,1] + x points[,2] = points[,2] + y } # generate about 1000 points with center(1,1) and radius 3 points = f(1, 1, 3, 1000) # plot them, making them smaller for better visibility plot(points, cex=0.3)

**Random Uniformly Distributed Points in a Circle,** The point is that the area of the circle of radius r is πr2, and you want the probability of distance ≤r from the centre to be proportional to that area. Then simply call that in a list comprehension to generate however many points you desire. points = [random_point_within(poly) for i in range(5)] checks = [point.within(poly) for point in points] My approach is to select x randomly within the polygon, then constrain y. This approach doesn't require NumPy and always produces a point within the

Not sure what you mean 'uniformly'.

Here is one approach to generate 'uniformly' distributed points along x- and y-axis, but not very efficient

import numpy as np import matplotlib.pyplot as plt x = np.random.random(size) * 2 - 1 y = np.random.random(size) r = np.sqrt(x**2 + y**2) x[r > 1] = -3 y[r > 1] = -3 plt.plot(x, y, 'o') plt.show()

**Generating random points near a location,** To generate points uniformly, randomly, and independently within a circle of radius r around a location (x0, y0), start by generating two� There are in-built functions in R to generate a set of random numbers from standard distributions like normal, uniform, binomial distributions, etc. In the next section we will see different functions like runif (), rnorm (), rbinom () and rexp () to generate random numbers. Popular Course in this category

You can try out following in R:

size <- 1000 maxRad <- 1 #maximum radius of the half-circle r <- runif(1000,0,maxRad) #generate random radius phi <- runif(size,0,pi) #generate angle for polarcoordinates (between 0 and pi since you want a halfcircle) x <- r*cos(phi) #polarcoordinates y <- r*sin(phi) plot(x,y)

You can put it in a function

halfCircle <- function(size, maxRad) { r <- runif(1000,0,maxRad) phi <- runif(size,0,1)*pi x <- r*cos(phi) y <- r*sin(phi) plot(x,y) }

and try out whether it delivers you "more acceptable random" results.

**Generating a random point within a circle (uniformly),** For a circle of radius R, you use R*sqrt(rand()) for the radius, and rand()*2π for the angle. If needed, use cos/sin to convert it to Cartesian coordinates. random.uniform () to get a random float number within a range The random.uniform () function returns a random floating-point number between a given range in Python. Let’s assume you want to generate a random float number between 10 to 100 Or from 50.50 to 75.5. In such cases, you should use random.uniform () function.

**Random Number Generation and Sampling Methods,** ways to generate uniform random numbers from an underlying RNG (such as the core Sample Python code that implements many of the methods in this document is Random Points Inside a Box; Random Points Inside a Simplex; Random while not done // Update each chain with the same randomness r= RANDOM()� The answer depends on what kind of random number you want to generate. Let's illustrate by example. Generate a random number between 5.0 and 7.5 If you want to generate a decimal number where any value (including fractional values) between the stated minimum and maximum is equally likely, use the runif function.

**Generating uniformly distributed numbers on a sphere ,** So, we want to generate uniformly distributed random numbers on a unit sphere. In spherical coordinates, r is the radius, θ∈[0,2π] is the azimuthal angle, and ϕ ∈[0,π] is the polar angle. Set up random number generators Let v be a point on the unit sphere S. We want the probability density f(v) to be� The random choice from a set in Python. If we pass Set object directly to the choice function we will get the TypeError: ‘set’ object does not support indexing. Using the random.choice function we can’t choose random items directly from a set, without having to copy it into a tuple. Let see how to use a choice function to select a random

**Generating Random Points in a Sphere,** Visualization of different methods of generating random points inside a sphere. We also need a way to pick a random point in a unit radius sphere This gives a well-distributed collection of points, but about 48% of the points part of a semi- circle: choosing a uniformly random point on the curve is what� To generate numbers from a normal distribution, use rnorm().By default the mean is 0 and the standard deviation is 1.

##### Comments

- I think you can't get absolute uniformity because of mathematical reasons, see en.wikipedia.org/wiki/Circular_uniform_distribution, last paragraph in Distribution of the mean: "It follows that they will have zero mean and a variance of 1/2".
- The circle or mean and variance has nothing to do with it? Even uniform points on a square will have a zero mean and some variance? I view uniformity here as how the points are spaced relative to one another within this area.
- thanks for the link, it does not have to be absolute uniformity. relatively uniformity is acceptable.
- Possible duplicate of Generate a random point within a circle (uniformly)
- thanks! your answer is so helpful! and what does the variable name 'sims' mean, simulator?
- This should be the accepted answer as it does not waste any of the points generated.
- It is appreciated if you could add the maths behind to explain why square root is used?
- Considering how slow calculating large numbers of square roots is, I wouldn't be suprised if this is slower than a rejection algorithm. It is however, much more elegant.
- @DanielF Using
`numpy`

, the`sqrt`

will be a vectorized operation on the whole array. It cannot get much faster than that. - @JanChristophTerasa, You can't do square root faster than that, true. But a rejection algorithm eliminates the square root step entirely, at the cost of elegance and absolute process stability.
- thanks for your hint, though, it seems to be NOT uniformly
- In my testruns it seems like the points tend to center in the coordinate origin. See the wikipedia article en.wikipedia.org/wiki/Circular_uniform_distribution. In the last paragraph in "Distribution of the mean" it is stated that "... they will have zero mean and a variance of 1/2" so you will have something that looks not uniformly, because of mathematical reasons.
- This is not correct. You have to sample
`r`

according to the*square root*of the uniform distribution.