计算椭圆内的点数

2024-09-26 22:52:03 发布

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

我试着计算每个椭圆环内给定的数据点:

enter image description here

问题是我有一个函数来检查: 因此,对于每个椭圆,要确定其中是否有一个点,必须计算三个输入:

def get_focal_point(r1,r2,center_x):
    # f = square root of r1-squared - r2-squared
    focal_dist = sqrt((r1**2) - (r2**2))
    f1_x = center_x - focal_dist
    f2_x = center_x + focal_dist
    return f1_x, f2_x

def get_distance(f1,f2,center_y,t_x,t_y):
    d1 = sqrt(((f1-t_x)**2) + ((center_y - t_y)**2)) 
    d2 = sqrt(((f2-t_x)**2) + ((center_y - t_y)**2))
    return d1,d2

def in_ellipse(major_ax,d1,d2):
    if (d1+d2) <= 2*major_ax:
        return True
    else:
        return False

现在我正在检查它是否在椭圆中,方法是:

^{pr2}$

但我必须计算出外环的每对焦点。。 有没有更有效或更聪明的方法来做到这一点?在


Tags: getreturndistdefsqrtf2f1d2
3条回答

这可能与你正在做的事情类似。我只是想看看 f(x,y)=x^2/r1^2+y^2/r2^2=1。在

当f(x,y)大于1时,点x,y在椭圆外。当它较小时,它在椭圆内。当f(x,y)小于1时,我遍历每个椭圆,找出一个。在

代码也不考虑偏离原点的椭圆。加入这个功能只是一个小小的改变。在

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np

def inWhichEllipse(x,y,rads):
    '''
    With a list of (r1,r2) pairs, rads, return the index of the pair in which
    the point x,y resides. Return None as the index if it is outside all 
    Ellipses.
    '''
    xx = x*x
    yy = y*y

    count = 0
    ithEllipse =0
    while True:
        rx,ry = rads[count]
        ellips = xx/(rx*rx)+yy/(ry*ry)
        if ellips < 1:
            ithEllipse = count
            break
        count+=1
        if count >= len(rads):
            ithEllipse = None
            break

    return ithEllipse

rads = zip(np.arange(.5,10,.5),np.arange(.125,2.5,.25))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(-15,15)
ax.set_ylim(-15,15)

# plot Ellipses
for rx,ry in rads:
    ellipse = patches.Ellipse((0,0),rx*2,ry*2,fc='none',ec='red')    
    ax.add_patch(ellipse)

x=3.0
y=1.0
idx = inWhichEllipse(x,y,rads)
rx,ry = rads[idx]
ellipse = patches.Ellipse((0,0),rx*2,ry*2,fc='none',ec='blue')    
ax.add_patch(ellipse)

if idx != None:
    circle = patches.Circle((x,y),.1)
    ax.add_patch(circle)

plt.show()

此代码生成下图: enter image description here

记住,这只是一个起点。首先,您可以更改inWhichEllipse以接受r1和r2的平方,即(r1*r1,r2*r2)对的列表,这将进一步减少计算量。在

你让事情复杂化了。根据椭圆的几何定义,不需要计算焦点和到焦点的距离等。如果你知道长轴和短轴(你知道),就把整个问题压缩一点(这样两者都是1.0,例如,用x轴和y轴除以x轴和y轴),然后这个点是否在椭圆内的问题就简单了

xnormalized**2 + ynormalized**2 <= 1

注:一般来说,这个领域的好建议是:不,sqrt如果你能做同样的事情,不计算一个距离,而是舒服地呆在它的平方域内。在

以下是一些给你的建议:

  • 将计算焦点的代码移到循环之外是正确的。在
  • 去除平方根可以加快距离计算。换句话说,我们知道a < b意味着sqrt(a) < sqrt(b),所以不需要计算平方根。在
  • 如果椭圆是同心的并且长轴与x轴平行,则可以通过重新调整x值将椭圆问题简化为圆问题。在

另外,这里还有一个小的编码问题。不需要if语句返回TrueFalse。相反,可以返回条件表达式本身:

def in_ellipse(major_ax,d1,d2):
    return (d1+d2) <= 2*major_ax:

相关问题 更多 >

    热门问题