2018년 5월 21일 월요일

[python] 파이계산및그래프그리기

import random
import math
import matplotlib.pyplot as plt

xset = []
yset = []

def generateSamples(size):
    xset.clear()
    yset.clear()
 
    for i in range(size):
        x = random.random()
        y = random.random()
        xset.append(x)
        yset.append(y)

def isInsideCircle(x, y):
r = 0.5
distance = (x - 0.5)*(x - 0.5) + (y - 0.5)*(y - 0.5) - r*r
if (distance >= 0.0):
return False
else:
return True

def estimatePi():
    circles = 0
    squares = len(xset)
    x_circle=[]
    y_circle=[]
    for i in range(squares):
        x = xset[i]
        y = yset[i]
        if (isInsideCircle(x, y)==True):
            circles += 1
            x_circle.append(x)
            y_circle.append(y)
        pi = 4 * circles / squares

    plt.scatter(x_circle, y_circle)
    plt.show()

    return pi

def main():
    pi = []
    nums=[]
    for i in range(10000, 10001, 1):
        generateSamples(i)
        p = estimatePi()
        pi.append(p)
        nums.append(i)
        print("%1.20f"%p)
    plt.plot(nums, pi, 'ro')
    plt.axis([0, 10000, 3, 3.3])
    plt.show()

main()

댓글 없음:

댓글 쓰기