蒙特卡罗方法求圆周率

2022-07-05  本文已影响0人  codeduck1
# -*- 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)

上一篇 下一篇

猜你喜欢

热点阅读