Blub21
Blub21

Reputation: 17

Calculating pi with Python

I tried to write a python script to calculate pi. I know there are hundreds out there that could do it for me but that defeats the purpose of learning, hence the question.

I found a way to calculate pi on the following site: https://nl.wikihow.com/Pi-berekenen it's the first from method 2. The site is in Dutch, I'm sorry. The way I want to do it is also explained in this youtube video: https://www.youtube.com/watch?v=HrRMnzANHHs&t=8s (that is english).

I tried the following script:

from decimal import *
def fractions():
    fractions = input("How many fractons to add")
    return fractions

fractions = fractions()


def calculate(fractions):
    fractions = fractions
    i=0 
    x=1
    total = Decimal(0)  
    plus = True
    while i < fractions:
        if plus:
            total = Decimal(total) + Decimal(4/x)
            plus = False
        else:
            total = Decimal(total) - Decimal(4/x)   
            plus = True
        print Decimal(total)
        print x
        print plus
        i= i + 1
        x= x + 2
    return Decimal(total)


pi = calculate(fractions)
print pi

But it only outputs the following: Output from code

I don't know why it keeps hanging at 3, because if it rounds the numbers it should go to 2 atleast 1 time in this sequence.

So the question is, what's wrong in my code?

Upvotes: -1

Views: 1725

Answers (1)

Kazber
Kazber

Reputation: 23

I didn't watch the video but the one thing I noticed in your code is how you handle the data from the input in the first function. When you get the number of fractions from input(), it’s coming in as a string, so that’s why the loop isn’t working right. You need to convert it to an integer, otherwise, the while loop gets confused because you're comparing a string to a number, which won’t work properly.

fractions = int(fractions)

Upvotes: 0

Related Questions