Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Different result from while loop than when in a user defined function

I am trying to create a code that returns a approximation of pi given n iterations that the user will give. The higher n the more accurate.

I created a while loop to do this, and it works fine:

import math

x = 1
k = 0
n = int(input("Enter n:"))
while x <= n:
    k=k+(1/x**2) # summation of 1/k**2 for every n times
    y=k*6 # multiply k by 6 like in formula
    fin = math.sqrt(y) # find sqrt of y like in the formula
    x += 1

print(fin)

But now I’m trying to make this into a function. This is what I’ve come up with:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import math

def pi(n):
    x = 1
    k = 0
    #n = int(input("Enter n:"))
    while x <= n:
        k=k+(1/x**2) # summation of 1/k**2 for every n times
        y=k*6 # multiply k by 6 like in formula
        fin = math.sqrt(y) # find sqrt of y like in the formula
        x += 1
        return fin

g=pi(int(input("Enter n:")))
print(g)

For some reason I get different answers… why is it when I use the function that the answer becomes inaccurate?

>Solution :

You have your return inside the loop, hence the block inside the while is executed only once and the rest of approximations are never calculated, put your return out of your cycle:

while x <= n:
    k=k+(1/x**2) # summation of 1/k**2 for every n times
    y=k*6 # multiply k by 6 like in formula
    fin = math.sqrt(y) # find sqrt of y like in the formula
    x += 1
return fin

I tested it, now it returns the same result with both approaches.

Have a good day! 😀

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading