使用 Monte Carlo 在 (0≤≤1,0≤≤1) 范围内至少两个圆的交集区域

area of intersection of at least two circles in a range of (0≤≤1,0≤≤1) using Monte Carlo

我想使用Monte Carlo在这个范围内(0≤≤1,0≤≤1)找到至少两个圆的交点区域。这是我到目前为止所做的。

import matplotlib.pyplot as plt

# Making a class circle and initializing it with its centre and radius
class circle:
    def __init__(self,radius,x,y):
        self.radius = radius
        self.x = x
        self.y = y

#Finding point that lies inside the circle
    def exist_in_circle(self,x1,y1):
        if (self.x-x1)(self.x-x1)+(self.y-y1)(self.y-y1) < self.radius*self.radius :
            return True
        else:
            return False

# initializing plt of matplotlib
fig, ax = plt.subplots()
ax.set(xlim=(-1, 2), ylim = (-1, 2))


# initializing 3 circles as required in the question
c1 = circle(1,1,0.5)
c2 = circle(0.5,0.5,0.5)
c3 = circle(0.4,0.1,0.1)

# plotting circles and a square from (0,0) to (1,1)
a_circle = plt.Circle((c1.x, c1.y), c1.radius,color='r', linewidth=1, fill=False)
ax.add_artist(a_circle)
a_circle = plt.Circle((c2.x, c2.y), c2.radius,color='b', linewidth=1, fill=False)
ax.add_artist(a_circle)
a_circle = plt.Circle((c3.x, c3.y), c3.radius,color='g', linewidth=1, fill=False)
ax.add_artist(a_circle)
ax.add_patch(plt.Rectangle((0,0), 1, 1,color="k", linewidth=1, fill=False))



# Printing the graph
plt.show() 

这是我当前的输出。

这是我使用的预期输出。

关于如何使用 Monte Carlo 方法解决它的任何技术或方法。提前致谢!!

要首先使用蒙特卡洛方法,您需要生成 1x1 网格

import numpy as np
x = np.linspace(0, 1, 100)
y = np.linspace(0, 1, 100)
xx, yy = np.meshgrid(x, y)
print(x.shape, y.shape, xx.shape, yy.shape)
(100,) (100,) (100, 100) (100, 100)

然后您需要一个函数来告诉您点是位于所需区域的内部还是外部。我使用了您提供的示例中的逻辑,但如果使用其他交集规则,则应更改此功能。

def in_area(point):
    if c1.exist_in_circle(*point) and c2.exist_in_circle(*point):
        return True
    if c1.exist_in_circle(*point) and c3.exist_in_circle(*point):
        return True
    return False

然后你遍历点并创建一个二进制列表来计算所需区域内的点。

c = []
for x, y in zip(np.ravel(xx), np.ravel(yy)):
    is_in_area = in_area((x, y))
    c.append(is_in_area)

要计算面积,只需计算区域内点的比例即可。重要提示:我们在 1x1 标识正方形内使用点,因此我省略了缩放它的步骤,因为该正方形的面积为 1。

area = sum(c)/len(c)
print(area)
0.8002

然后将这些行添加到您之前的可视化代码中,然后绘制结果。

colors = list(map(lambda x: {True: 'b', False: 'w'}[x], c))
plt.scatter(np.ravel(xx), np.ravel(yy), c=colors)
plt.title(f'Area: {area}')
plt.show()

该区域充满了密集的点 - 它不是完整的形状。