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

import random

def estimate_pi(n):
    num_points_inside_circle = 0
    num_points_total = n
    
    for i in range(num_points_total):
        x = random.uniform(0, 1)
        y = random.uniform(0, 1)
        
        if x**2 + y**2 <= 1:
            num_points_inside_circle += 1
            
    return 4 * num_points_inside_circle / num_points_total

print(estimate_pi(1000000))

这个代码使用了蒙特卡罗方法来估计圆周率。该方法基于以下原理:假设我们有一个正方形,其边长为 2,以及一个内切于该正方形的圆。如果我们在正方形中随机选择一个点,那么该点在圆内的概率为 π/4。因此,我们可以随机选择一些点并计算有多少个点在圆内,从而估计出 π 的值。

在上面的代码中,我们随机选择了一百万个点,并计算有多少个点在内切圆内。最后,我们将估计出的值乘以 4,以得到最终的估计值

帮我写一个python代码计算圆周率

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

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