-2

Hi I want to generate 100 random sample data for x1 and x2 with numpy library,that satisfy below conditions. ( 1 < x1^2 + x2^2 < 2 )

  • 1
    What have you tried so far? – Mr. Polywhirl Feb 20 '23 at 19:37
  • 1
    The angle is obviously uniform between 0 and 2π. As for the radius distribution, you must use the [Inverse Transform Method](https://en.wikipedia.org/wiki/Inverse_transform_sampling). See for example [this SO answer about a very similar problem](https://stackoverflow.com/a/9048443/11282404). – jpmarinier Feb 20 '23 at 19:56

2 Answers2

2

Recognize that a vector with components x1 and x2 has a magnitude of sqrt(x1**2 + x2**2). You want a random vector with a magnitude between 1 and √2

You can generate random vectors, normalize them so that their magnitudes are 1, then multiply them by a random number between 1 and √2.

import numpy as np

# generate 100 random 2d vectors
vecs = np.random.random((100, 2))

# normalize them to a magnitude of 1
vecs /= np.linalg.norm(vecs, axis=1, keepdims=True)

# generate 100 random magnitudes
mags = np.random.uniform(1, np.sqrt(2), (100, 1))

# multiply unit vectors by random magnitudes
vecs *= mags

# separate into components 
x1 = vecs[:, 0]
x2 = vecs[:, 1]

Finally, let's make sure our condition holds:

v = x1**2 + x2**2
assert ((v >= 1) & (v <= 2)).all()

Try it online!

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
-1
import numpy as np

# Define the number of samples you want to generate
num_samples = 100

# Define the lower and upper bounds for x1 and x2
lower_bound = -2**0.5
upper_bound = 2**0.5

# Initialize an empty array to store the generated samples
samples = np.empty((num_samples, 2))

# Generate random samples until we have num_samples that satisfy the condition
count = 0
while count < num_samples:
    # Generate a random pair of values for x1 and x2 within the bounds
    x1, x2 = np.random.uniform(lower_bound, upper_bound, 2)
    
    # Check if the condition is satisfied for the pair
    if 1 < x1**2 + x2**2 < 2:
        # If the condition is satisfied, add the pair to the array
        samples[count] = [x1, x2]
        count += 1

# Print the generated samples
print(samples)