'Having a loop issue
I am running the following code for pi value to calculate the first value which yields 3.14. I used manual values for range which works, but I want the values to be incremental to give me the first value. My code has a loop, and I know its a minor fix.
sum = 0
denominator = 1
counter = 1
while '3.14' not in str(sum):
for i in range(counter):
print(counter)
if i % 2 == 0:
sum += 4/denominator
else:
sum -= 4/denominator
denominator += 2
if '3.14' in str(sum):
print(f'The iteration is {i+1} and the values is {sum}')
break
counter += 1
Solution 1:[1]
So it looks like you're trying to find the value of ? by using the Leibniz equation, ?/4 = 1 - 1/3 + 1/5 - 1/7
Oh, and don't name variables sum. It's an important built-in function.
import itertools
total = 0
# denominator will take the values 1, 3, 5, 7, 9, ...
for denominator in itertools.count(1, 2):
if denominator % 4 == 1:
total += 4 / denominator
else:
total -= 4 / denominator
if 3.14 <= total < 3.15:
return denominator
Solution 2:[2]
There were two errors actually.
You have to subtract at even places and add at odd. So that had to be reversed.
There was no need of a second for loop. The first while is enough. It can be solved by the integer method but since you used the string method the refined code should be:
sum = 0 denominator = 1 counter = 1 #this is the main loop while '3.14' not in str(sum): #print(counter) if counter % 2 != 0: sum += 4/denominator print('sum=', sum) else: sum -= 4/denominator denominator += 2 if '3.14' in str(sum): print(f'The iteration is {counter+1} and the values is {sum}') break counter += 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frank Yellin |
| Solution 2 |
