meowdog011011
meowdog011011

Reputation: 1

Why is my Python Pi calculator slowing down over time?

I recently saw this video that explained how to calculate pi, and attempted to build a Python simulation. In theory, it works, but it is much too slow, and I have no idea why.

In the output, you can see that the program starts off with hundreds of collisions calculated per second, but quickly slows down to only 40-50 per second, and when I leave it alone for a prolonged amount of time, it decreases to a measly 2 calculations! Here is my code:

#imports
from time import time, sleep
from fractions import Fraction

#set variables
p = [Fraction(8, 1), Fraction(10, 1)]
m = [1, 1]
v = [Fraction(0, 1), Fraction(-1, 1)]
collisions = 0
time_interval = 1

#main
print("The π Calculator\n\nCredits:\nOriginal formula discovered by Gregory Galperin\nSimulation by Te Du\n")
sleep(1)
m[1] = 100 ** int(input("How many digits would you like to calculate? "))
start_time = time()
prev_time = start_time
while not (v[0] <= v[1] and v[0] >= 0):
    if time() - prev_time >= time_interval:
        try:
            print("Seconds elapsed: " + str(time() - start_time) + "\nCollisions: " + str(collisions))
        except ValueError:
            prev_time = time() + 1000000000
        time_interval = 2 - (time() - prev_time)
        prev_time = time()
    try:
        wall_to_one = p[0] / -v[0]
    except ZeroDivisionError:
        wall_to_one = 0
    one_to_two = (p[1] - p[0]) / (v[0] - v[1])
    collisions += 1
    if one_to_two <= 0 or (0 < wall_to_one and wall_to_one < one_to_two):
        p[0] += v[0] * wall_to_one
        p[1] += v[1] * wall_to_one
        v[0] *= -1
    else:
        p[0] += v[0] * one_to_two
        p[1] += v[1] * one_to_two
        v = [Fraction(m[0] - m[1], m[1] + m[0]) * v[0] + Fraction(2 * m[1], m[1] + m[0]) * v[1], Fraction(2 * m[0], m[1] + m[0]) * v[0] + Fraction(m[1] - m[0], m[1] + m[0]) * v[1]]

#cleanup
del p, m, v, wall_to_one, one_to_two, start_time, prev_time, time_interval

#printing pi
print("π: " + str(collisions))

Upvotes: 0

Views: 64

Answers (0)

Related Questions