美文网首页π
2018-12-02 Π值的运算(蒙特·卡罗方法)

2018-12-02 Π值的运算(蒙特·卡罗方法)

作者: 子小亦大 | 来源:发表于2018-12-02 21:11 被阅读0次

    Π值的运算(蒙特·卡罗方法)

    蒙特·卡罗方法(Monte Carlo method),也称统计模拟方法

    #CalPI.py

    from random import random

    from time import perf_counter

    drafts = 10000000

    hits = 0.0

    start = perf_counter()

    for i in range(1,drafts+1):

        x,y = random(),random()

        l = pow(x**2 + y**2, 0.5)

        if l < 1.0:

            hits = hits + 1

    PI = 4 * hits / drafts

    print("the PI is {}".format(PI))

    print("the time is {}s".format(perf_counter()-start))

    相关文章

      网友评论

        本文标题:2018-12-02 Π值的运算(蒙特·卡罗方法)

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