美文网首页
蒙特卡罗方法求圆周率

蒙特卡罗方法求圆周率

作者: codeduck1 | 来源:发表于2022-07-05 18:45 被阅读0次
# -*- coding=utf-8 -*-
# @PROJECT_NAME: day01 
# @FILE: demo02.py
# @Time: 7/6/2022 6:27 PM
# @Author: code_duck
# @Software: PyCharm

import random
# 蒙特卡罗方法求圆周率
from functools import reduce


def estimate_pi(times):
    hists = 0
    for i in range(times):
        x = random.random() * 2 - 1
        y = random.random() * 2 - 1
        if x * x + y * y <= 1:
            hists += 1
    return 4.0 * hists / times


if __name__ == "__main__":
    result_list = [estimate_pi(100000) for i in range(10)]
    avg = reduce(lambda a, b: a + b, result_list) / len(result_list)
    print(avg)

相关文章

网友评论

      本文标题:蒙特卡罗方法求圆周率

      本文链接:https://www.haomeiwen.com/subject/fibybrtx.html