Buffon's needle simulation in python

后端 未结 6 1484
臣服心动
臣服心动 2021-01-27 18:47
import numpy as np
import matplotlib.pylab as plt

class Buffon_needle_problem:

    def __init__(self,x,y,n,m):
        self.x = x #width of the needle
        self.y =         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-27 19:11

    I used Python turtle to approximate the value of Pi:

    from turtle import *
    from random import *
    
    setworldcoordinates(-100, -200, 200, 200)
    ht(); speed(0); color('blue')
    
    drops = 20  # increase number of drops for better approximation
    hits = 0    # hits counter
    
    # draw parallel lines with distance 20 between adjacent lines
    for i in range(0, 120, 20): 
        pu(); setpos(0, i); pd()
        fd(100) # length of line
    
    # throw needles
    color('red')
    for j in range(drops):
        pu()
        goto(randrange(10, 90), randrange(0,100))
        y1 = ycor() # keep ycor of start point
        seth(360*random())
        pd(); fd(20)    # draw needle of length 20
        y2 = ycor() # keep ycor of end point
    
        if y1//20 != y2//20:    # decisive test: if it is a hit then ...
            hits += 1       # increase the hits counter by 1
    
    print(2 * drops / hits)
    
    Output samples
    With 50 drops   3.225806451612903
    with 200 drops  3.3057851239669422
    with 1000 drops 3.1645569620253164
    

提交回复
热议问题