Home > Mobile >  Python - Different result from while loop than when in a user defined function
Python - Different result from while loop than when in a user defined function

Time:02-17

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:

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?

CodePudding user response:

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! :D

  • Related