dimanche 13 septembre 2020

Buffons needle simulation using turtle. I can not get my if else statement to change the color of the needles?

I am trying to recreate Buffon's needle simulation in python3 for a class. What I came up with seems to do a good job of estimating pi but I am having trouble with my if-else statement. What I want is to have the needles turn red if they intersect one of the black lines, and turn blue if they do not (see picture link). It seems to assign a color to a needle randomly, and I am not sure why this is. Help with this issue would be greatly appreciated! :)

enter image description here

import math
import turtle
import random
from math import pi, cos, sin

def BuffonNeedles(numNeedles):

    wn = turtle.Screen()
    georgie = turtle.Turtle()

    wn.setworldcoordinates(-2, -2, 2, 2)

    georgie.up()
    georgie.goto(-2, 0)
    georgie.down()
    georgie.goto(2, 0)

    georgie.up()
    georgie.goto(-2, 1)
    georgie.down()
    georgie.goto(2, 1)

    numHit = 0

    for i in range(numNeedles):
        x = random.random()
        y = random.random()
        angle = random.random() * 180

        formula1 = float(math.sin(math.radians(angle)) / 2)
        point1 = y + formula1
        point2 = y - formula1

        if point1 >= 1 or point2 <= 0:
            numHit = numHit + 1
            georgie.color("red")

        else:
            georgie.color("blue")

        georgie.up()
        georgie.goto(x, y)
        georgie.right(angle)
        georgie.down()
        georgie.forward(1)

    pi = 2 * (numNeedles / numHit)
    wn.exitonclick()

    print(pi)
    return pi

BuffonNeedles(1000)

Aucun commentaire:

Enregistrer un commentaire