以下是用蒙特卡罗方法计算圆周率π的Python代码:

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个点,然后计算这些点与圆心的距离,如果距离小于等于1,则认为该点在圆内。最后,根据圆内点的数量和总点数,计算出圆周率π的近似值。

写出算计算圆周率π的代码用python写

原文地址: https://www.cveoy.top/t/topic/hsiT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录