<p>可以使用<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html" rel="nofollow noreferrer">^{<cd1>}</a>直接计算周长上的点。从左到右计算<code>x</code>,从下到上计算<code>y</code>,可以使用以下方法:</p>
<pre><code>import numpy as np
def square(top_left, l, n):
top = np.stack(
[np.linspace(top_left[0], top_left[0] + l, n//4 + 1),
np.full(n//4 + 1, top_left[1])],
axis=1
)[:-1]
left = np.stack(
[np.full(n//4 + 1, top_left[0]),
np.linspace(top_left[1], top_left[1] - l, n//4 + 1)],
axis=1
)[:-1]
right = left.copy()
right[:, 0] += l
bottom = top.copy()
bottom[:, 1] -= l
return np.concatenate([top, right, bottom, left])
</code></pre>
<p>例如:</p>
<pre><code>import matplotlib.pyplot as plt
s = square((0, 0), 2, 400)
plt.plot(s[:, 0], s[:, 1], 'o')
plt.grid()
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/dT4Ou.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dT4Ou.png" alt="Square"/></a></p>
<hr/>
<p>如果出于任何原因不能使用numpy,那么(重新)创建所需的功能也不会太麻烦(例如,请参阅<a href="https://github.com/numpy/numpy/blob/d1e0a43ff910e15034997b9b646b38014382fe6e/numpy/core/function_base.py#L28" rel="nofollow noreferrer">^{<cd1>}</a>的源代码作为方向):</p>
<pre><code>def linspace(a, b, n):
return [a + (b - a) / (n - 1) * i for i in range(n)]
def full(n, x):
return n * [x]
def square(top_left, l, n):
top = list(zip(
linspace(top_left[0], top_left[0] + l, n//4 + 1),
full(n//4 + 1, top_left[1])
))
left = list(zip(
full(n//4 + 1, top_left[0]),
linspace(top_left[1], top_left[1] - l, n//4 + 1)
))
right = [(x + l, y) for x, y in left]
bottom = [(x, y - l) for x, y in top]
return top + right + bottom + left
</code></pre>