我目前正在尝试找出如何返回正方形的周长,然后将其用作计算电荷密度的输入。具体地说,电荷在正方形周围是均匀的,然后用来计算电位和电荷密度。
这是我有的点数收费代码。
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
有什么建议吗?谢谢!
发布于 2018-11-30 08:01:51
可以使用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()
如果你因为某种原因不能使用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
发布于 2018-11-30 11:41:27
使用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.]]])
https://stackoverflow.com/questions/53548996
复制相似问题