Home > front end >  Having a loop issue
Having a loop issue

Time:02-04

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

CodePudding user response:

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

CodePudding user response:

@Frank Yellin

Thank you for the response. Could you modify my existing code, so that I know where exactly the loop lies? My code works for manual values, like if I were to enter a manual range, say 200, it stops the iteration at 119. I want to use the counter logic in incremental fashion.

CodePudding user response:

There were two errors actually.

  1. You have to subtract at even places and add at odd. So that had to be reversed.

  2. 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
    
  •  Tags:  
  • Related