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 )
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()