python - 如何以数组形式返回正方形上的点?

标签 python geometry

我目前正在尝试找出如何返回正方形的周长,然后将其用作计算电荷密度的输入。具体来说,正方形周围的电荷是均匀的,然后用于计算电势和电荷密度。

这是我用于积分收费的代码。

def Q(i,j,x_max,y_max,delta):
     x_dist=math.exp(-(i*delta-x_max/2.0)*(i*delta-x_max/2.0)/(1.0*delta*delta))
     y_dist=math.exp(-(j*delta-y_max/2.0)*(j*delta-y_max/2.0)/(1.0*delta*delta))
     return x_dist*y_dist

我发现了这个非常有趣的网站,它暗示我可以通过使用方程 x^(一个非常大的数)+ y^(一个非常大的数)= 1 来近似一个平方来完成这个任务。这引起了我的兴趣,因此我尝试在正方形上创建点作为电荷源。

http://polymathprogrammer.com/2010/03/01/answered-can-you-describe-a-square-with-1-equation/

我已经尝试了以下方法,但当然,这只返回一分。

return math.pow(x_dist,1000000)-1

有什么建议吗?谢谢!

最佳答案

您可以使用 np.linspace 直接计算周长上的点。从左到右计数 x 和从下到上计数 y,您可以使用以下内容:

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

例如:

import matplotlib.pyplot as plt

s = square((0, 0), 2, 400)
plt.plot(s[:, 0], s[:, 1], 'o')
plt.grid()
plt.show()

Square


如果您出于某种原因无法使用 numpy,(重新)创建所需程度的功能并不会太麻烦(例如,请参阅 np.linspace 的源代码作为方向):

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

关于python - 如何以数组形式返回正方形上的点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53548996/

相关文章:

constructor - “object”不包含带有 3 个参数的构造函数

python - 我如何创建 turtle 克隆并将它们附加到列表中?

python - 计算从给定日期算起固定天数的日期

python - 使用 ExceltoCi 将数据加载到 Peoplesoft 数据库中

matlab - 如何将向量列表绘制为球体?

c - 中点圆算法不适用于不等中心坐标

python - 交叉 3D 网格 python

Python CSV 阅读器将行作为列表返回

c++ - 查找使用球坐标表示的线段之间的距离

c++ - 给定第一象限中的坐标列表,计算可以形成多少个单边平行于 x 轴的直角三角形