-2

I cannot determine my logic error,

Code:

import math

repeat = "y"    
factor = [5]    

def findFactor():
    res = factor[0]
    factor[0] += 2
    print(res)
    return res

while (repeat == "y"):

    tol = float(input("Please enter the tolerance: "))

    z = 6/math.sqrt(3)
    print(z)

    num1 = 1
    num2 = num1 - (1/3)
    i = 2
    diff = 999

    while math.fabs(diff) > tol:
        diff = (z *num2) - (z * num1)
        print("Num 1", (z *num1), " Num 2", (z *num2))
        print("Pi: ", (z * num2))
        num1 = num2
        add = (-1)**i/(3**i * findFactor())
        print(add)
        num2 = num2 + add
        i += 1
        print("Diff", diff)
    print("We got: ", z * num2, " for pi")
    repeat = input("Continue? (Y/N)").lower()

It seems to work in the start of the execuation and then just way undershoots pi.

Formula

zero323
  • 322,348
  • 103
  • 959
  • 935
JPHamlett
  • 365
  • 3
  • 9
  • 1
    I don't have time to debug all your code, but one thing I find suspect is your `findFactor` function, it probably keeps increasing, you should probably reset it whenever you ask the user for new input. But you make it yourself much more difficult than needed. Just get rid of the `findFactor` function and replace it by an expression that you can calculate easily from `i`. – Bas Swinckels Jul 05 '15 at 20:58
  • please explain `factor = [5]`. What do you think that instruction does? – Pynchia Jul 05 '15 at 20:58
  • let me expand that: why do you need a list if all you do is using its first element? i.e. factor[0] – Pynchia Jul 05 '15 at 21:01
  • @Pynchia It seems that the OP wanted to increase the value of factor in the global scope from within the `findFactor` function, but than found out that this does not work for immutable integers. If you store it in a mutable container, like a list, it works. Pretty smart, but complete overkill for such a simple program and bad practice to use this sort of 'global variables', which was probably the source of the bug in the code ... – Bas Swinckels Jul 05 '15 at 21:09
  • @BasSwinckels alright thank you. It's so far from what you'd do normally that I could not picture it. – Pynchia Jul 05 '15 at 21:15

1 Answers1

0

Error is in line computing 2nd item in the row:

num2 = num1 - (1/3)

but it should be

num2 = num1 - (1/(3*3))

Also it would be nice to replace unnecessary function findFactor by plain variable that will increase by two each iteration.

Ivan
  • 960
  • 7
  • 15