下面的代码生成一组随机的x,y坐标,并使用一个椭圆方程来比较这些点中有多少点位于以(1,1)为中心的椭圆内以及围绕该椭圆构造的面积为2a * 2b的矩形其半长轴和半短轴是a和b,但是b是可变的,并且每一次都从列表b中获取一个值。我想拥有所有b的值,对于这些b而言,位于椭圆内的所有点与位于矩形内的点的比率之比大于0.5。
我面临的问题是,如果我检查b = 0.63的单个值。条件ellipse_points / rectangle_points大约等于0.5,但是当我遍历列表b并使用If语句获取ellipse_points / rectangle_points> 0.5的所有点时,我看不到任何接近0.63的值,而是从从1.2到1.9,我不明白为什么当我遍历b的值列表时,if语句似乎给出错误的值。请参考下一组代码,其中我将b的值设置为0.63并找到比率ellipse_points / rectangle_points
import numpy as np
x = np.random.uniform(0, 2, 10000) #generates random x coordinates
y = np.random.uniform(0, 2, 10000) #generates random y coordinates
ellipse_points, rectangle_points = 0, 0
a = 1
b = []
for i in range(1, 200):
b.append(i/100)
#print(b)
for p in b:
for i, j in zip(x, y):
if (((i - 1) ** 2) / a ** 2 + ((j - 1) ** 2) / p ** 2) < 1:
ellipse_points += 1
rectangle_points += 1
if ellipse_points/rectangle_point > 0.5:
print(p)
输出:1.2,1.21 ............. 1.9
#x = np.random.uniform(0, 2, 10000) #generates random x coordinates
y = np.random.uniform(0, 2, 10000) #generates random y coordinates
ellipse_points, rectangle_points = 0, 0
a = 1
b = 0.63
for i, j in zip(x, y):
if (((i - 1) ** 2) / a ** 2 + ((j - 1) ** 2) / b ** 2) < 1:
ellipse_points += 1
rectangle_points += 1
print(ellipse_points/rectangle_points)
输出0.5001
答案 0 :(得分:0)
如果我正确理解了您的问题,这是向量化解决方案。
它为椭圆内的点创建一个二进制掩码,计算掩码在True
处的位置,然后将其除以总点数。
# np.random.seed(42)
N = 10000
x = np.random.uniform(0, 2, N) #generates random x coordinates
y = np.random.uniform(0, 2, N) #generates random y coordinates
a = 1
b = 0.63
ratio = ((((x - 1)/a)**2 + ((y - 1)/b)**2) < 1).sum()/N
>>> print(ratio)
0.4954