python 正多边形数据发生器

cgfeq70w  于 2023-01-01  发布在  Python
关注(0)|答案(1)|浏览(122)

不知道怎么做。
编写一个函数C = make_means(k, radius),输出包含k均值的2D坐标的k x 2数据矩阵C(指以后生成的数据)数据生成器的平均值必须位于正多边形的顶点上(如果k=3,则多边形是等边三角形,如果k=6,则它是正六边形,编写自己的代码来确定给定半径值的正多边形顶点的位置中心在原点并内接正多边形的圆的(input radius)。多边形在x轴上的第一个点。
例如,make_means(3, radius=1)将生成:
[[1.,0.],
[-0.5,0.8660254],
[-0.5,-0.8660254]]
下面是我代码:

for i in range(0, 360, 72):
    theta = np.radians(i)
    mean = np.array([1., 0.])
    c, s = np.cos(theta), np.sin(theta)
    cov = np.array(((c, -s), (s, c)))
    C = np.random.multivariate_normal(mean, cov, size= 1000)
    #C
    plt.scatter(C[:, 0], C[:, 1])

但它似乎并不旋转。

fwzugrvs

fwzugrvs1#

您的代码中可能存在一些问题,例如:
1.未定义make_means函数。相反,代码使用np. random. multivariate_normal生成随机数据矩阵C
1.* * meancov变量不用于生成数据矩阵C。相反,使用默认均值(0,0)和单位协方差矩阵生成C矩阵。
1.* * plt. scatter
函数在循环内部被调用,但不清楚其用途。
但是,要生成具有所需顶点数(k)和半径(radius)的正多边形的均值,可以使用以下代码:

import numpy as np
import matplotlib.pyplot as plt
def make_means(k, radius):
    # Initialize the means matrix
    means = np.zeros((k, 2))
    # Compute the angle between vertices in the regular polygon
    angle = 360 / k
    # Set the first vertex at the origin # you may change [1,0]
    means[0] = [1, 0]
    # Compute the positions of the remaining vertices
    for i in range(1, k):
        theta = np.radians(angle * i)
        means[i, 0] = radius * np.cos(theta)
        means[i, 1] = radius * np.sin(theta)
    return means
# Test the function with k=3 and radius=1
means = make_means(3, radius=1)
print(means)
# Plot
plt.scatter(means[:, 0], means[:, 1])
plt.show()

我的输出:

[[ 1.          0.        ]
 [-0.5         0.8660254]
 [-0.5        -0.8660254]]

绘图结果:

相关问题