如何将正方形上的点作为数组返回?

2024-06-16 09:39:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试找出如何返回一个正方形的周长,然后将其作为计算电荷密度的输入。具体地说,电荷在正方形的周长上是均匀的,然后用来计算电势和电荷密度。你知道吗

这是我的积分收费代码。你知道吗

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

有什么建议吗?谢谢!你知道吗


Tags: 代码return网站distdef数字mathmax
2条回答

矩形和正方形可以很容易地使用numpy制作。如果需要矩形网格,可以将该模式用作种子并重复。 例如,生成一个5个单位的正方形

import numpy as np
dx = 5
dy = 5
X = [0.0, 0.0, dx, dx, 0.0]       # X, Y values for a unit square
Y = [0.0, dy, dy, 0.0, 0.0]
a = np.array(list(zip(X, Y)))

对于小多边形来说有点过分,但是einsum可以很容易地用于计算几何体的周长或数百或数千个坐标对。你知道吗

a = np.reshape(a, (1,) + a.shape)
diff = a[:, 0:-1] - a[:, 1:]
d_leng = np.sqrt(np.einsum('ijk,ijk->ij', diff, diff)).squeeze()
length = np.sum(d_leng.flatten())

因此,对于简单多边形(第一个和最后一个点是重复的,以确保闭合),坐标、边和总长度如下所示

d_leng
array([5., 5., 5., 5.])

length
20.0

a
array([[[0., 0.],
        [0., 5.],
        [5., 5.],
        [5., 0.],
        [0., 0.]]])

如果你需要一个不同的原点开始之前,这可以简单地完成。。。你知道吗

a + [10, 10]
array([[[10., 10.],
        [10., 15.],
        [15., 15.],
        [15., 10.],
        [10., 10.]]])

可以使用^{}直接计算周长上的点。从左到右计算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,那么(重新)创建所需的功能也不会太麻烦(例如,请参阅^{}的源代码作为方向):

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

相关问题 更多 >