在单位圆内生成的标记点

Labeling points, that a generated within a unit circle

假设我们要生成带有单位圆的标签。

完成了什么:我在单位圆内生成了第一个点并将其标记为 1。我在单位圆内生成了第二个点并将其标记为 0。

剩下的 k-2 个点我想按以下方式标记:如果一个点位于半个圆 1 -> 标记为 1。如果在半个圆 0 -> 则标记为 0 . 所以这意味着,在生成前 2 个点之后,我需要通过圆心画一条线来分隔前两个点。之后我们将新生成的点与这条线进行比较并标记它。 Python 怎么瘦?

保存两个角度中的一个,命名为saved_angle,对所有点xy,检查是否x * np.sin(saved_angle) - y * np.cos(saved_angle) < 0。这是一个代码示例:

import matplotlib.pyplot as plt
import numpy as np

plt.xlim([-1, 1])
plt.ylim([-1, 1])

# Get two random points, saving the angle of one.

length = np.random.uniform(0, 1)
angle = np.pi * np.random.uniform(0, 2)
x = np.sqrt(length) * np.cos(angle)
y = np.sqrt(length) * np.sin(angle)
plt.plot([x], [y], 'ko')

length = np.random.uniform(0, 1)
saved_angle = np.pi * np.random.uniform(0, 2)
x = np.sqrt(length) * np.cos(saved_angle)
y = np.sqrt(length) * np.sin(saved_angle)
plt.plot([x], [y], 'ko')

# Plot a bunch of random points, checking the condition.

for _ in range(100):
    length = np.random.uniform(0, 1)
    angle = np.pi * np.random.uniform(0, 2)
    x = np.sqrt(length) * np.cos(angle)
    y = np.sqrt(length) * np.sin(angle)
    plt.plot([x], [y], 'bo' if x * np.sin(saved_angle) - y * np.cos(saved_angle) < 0 else 'ro')

plt.show()

这个怎么样?

思路是在构建了前两个点x[0,:]x[1,:]后,分别标记为y[0] = 0y[1] = 1,就可以构建一个向量n 垂直于向量 x[0,:]x[1,:] 之间夹角的角平分线。这就是为什么这个向量构造为

n = x[0,:] / norm(x[0,:])  -  x[1,:] / norm(x[1,:])

之后,在角平分线的一侧,即 n 指向的一侧的点,然后向量被标记为 01 如果它i 在角平分线的另一边。点积 n.dot(x[i,:]) > 0 表示 x[i,:]n 点的角平分线的一侧。

import numpy as np
import matplotlib.pyplot as plt

k = 12
x = np.empty((k, 2), dtype=float)
y = np.empty(k, dtype=int)
n = np.array([0.,0.])
for i in range(k):
    if i < 2:        
        angle = np.pi * np.random.uniform(0, 2)
        x[i,:] = np.array([np.cos(angle), np.sin(angle)])
        n = n + ((-1)**i) * x[i,:]
        length = np.random.uniform(0, 1)
        x[i,:] = np.sqrt(length)*x[i,:]
        y[i] = i
    else:
        angle = np.pi * np.random.uniform(0, 2)
        length = np.random.uniform(0, 1)
        x[i,:] = np.array([np.cos(angle), np.sin(angle)])
        if n.dot(x[i,:]) > 0: 
            y[i] = 0 
        else: 
            y[i] = 1
        x[i,:] = np.sqrt(length) * x[i,:]



s = np.linspace( 0 , 2 * np.pi , 150 )
xc = np.cos( s )
yc = np.sin( s )

xl = np.linspace( -1, 1, 150)  
yl = (- n[0]/n[1]) * xl


figure, axes = plt.subplots( 1 )

axes.plot( xc, yc )
axes.plot(0, 0)
axes.plot( xl, yl )

axes.plot(x[y==1, 0], x[y==1, 1], 'ro')
axes.plot(x[y==0, 0], x[y==0, 1], 'bo')

axes.set_aspect( 1 )  
plt.show()