I am a beginner in python and programming and have already hit a roadblock while doing excercises on HTLCS.
The problem is to use Liebniz approximation to calculate the value of pi (3.14…).
Here is my pitty attempt to solve the question:
def myPi():
n = 0
value = ((-1) ** n)/(2 * n + 1)
runningtotal = 0
while True:
runningtotal += value
n += 1
value = ((-1) ** n)/(2 * n + 1)
runningtotal *= 4
return runningtotal
Of course, the Python interpreter shell never finishes my function because of while True, and I understand solutions like while n != 5000 also work, but I want Python to find the terminating point itself and return the result.
I attempted to run while statement until the value of runningtotal and that of the updated runningtotal are same at certain floating number, but failed because for some reason the last floating points of two values missed by one at each loop. (runningtotal: 3.14157, updated runningtotal: 3.14158 -> runningtotal: 3.14158, updated runningtotal: 3.14157 -> repeat).
This is my first question on this forum, so let me know if I didn’t make myself clear or violated the rules of Stackflow that I was unaware of.
Floating point numbers have inherent imprecision, and testing them for equality is a risky business. I would recommend using a small tolerance instead of testing for equality. Instead of
oldTotal == newTotal, test for something likeabs(oldTotal-newTotal)<0.0001(or whatever tolerance you like).