
points = [(r * math.cos(2 * math.pi / n * i), r * math.sin(2 * math.pi / n * i)) for i in range(n)]
# 初始化计数器,用于记录在圆内的点的个数
num_inside = 0
# 遍历每一个分割出来的扇形区域,检查其是否与圆相交
for i in range(n):
# 计算扇形区域的两个端点坐标
p1 = points[i]
p2 = points[(i + 1) % n]
# 计算扇形区域的中心点坐标
pc = ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)
# 计算扇形区域和圆心连线的长度
d = math.sqrt((pc[0] - center[0]) ** 2 + (pc[1] - center[1]) ** 2)
# 如果长度小于半径,则扇形区域与圆相交,计数器加1
if d <= r:
num_inside += 1
# 计算圆的面积和周长
area = r ** 2 * math.pi
circumference = 2 * r * math.pi
# 计算估算的圆面积和周长,并计算估算的圆周率
estimated_area = area * num_inside / n
estimated_circumference = circumference * num_inside / n
estimated_pi = estimated_circumference / (2 * r)
# 输出结果
print(f"估算的圆周率为:{estimated_pi}")
可以使用蒙特卡罗方法来求解圆周率,具体思路如下:
代码如下:
import random
def estimate_pi(n):
num_point_circle = 0
num_point_total = 0
for _ in range(n):
x = random.uniform(0, 1)
y = random.uniform(0, 1)
distance = x**2 + y**2
if distance <= 1:
num_point_circle += 1
num_point_total += 1
return 4 * num_point_circle / num_point_total
print(estimate_pi(1000000))
其中,参数n是生成的点的数量。在这个例子中,我们生成了1000000个点,得到的输出为:
3.142012
可以看到,我们得到了一个近似于圆周率的值。随着生成的点数越来越多,我们得到的结果会越来越接近真实的圆周率。
定义 HTML 页面中的图像