Pi Sequence

View as PDF

Submit solution


Points: 10 (partial)
Time limit: 1.0s
Memory limit: 32M

Author:
Problem type
Allowed languages
Python

The number \pi is a mathematical constant that is the ratio of a circle's circumference to its diameter, approximately equal to 3.14159. The following series can be used to approximate this number (when k goes large):


\pi \approx \sum_{0}^{k}\frac{(-1)^i4}{2(i+1)-1}

In this programming problem, you are required to write a generator function named Pi_seq that generate the first k terms in the series.

You can start with this template code and ensure your code can run correctly within this template:

def Pi_seq(k):
    # your code here

# Note that the following code is for local testing purposes only. You should leave this part of code unchanged and not submit it to the OJ system.
T = int(input())
for t in range(T):
    k = int(input())
    Pi_gen = Pi_seq(k)
    Pi = 0
    term = next(Pi_gen, None)
    while term != None:
        Pi += term
        term = next(Pi_gen, None)
    print(f'{Pi:.6f}')

Please note that you only have to submit the definition of the Pi_seq function to the OJ system. The rest of the code is for your local testing purposes only.

Input Specification

The first line of the input gives the number of test cases, T, and then T test cases follow.

For each test case, it will consist of a single line that contains an integer k.

Constraints

1 \leq T \leq 100

1 \leq k \leq 10000

Output Specification

For each test case, output a single line containing the approximate value of \pi using the first k terms of the series.

Sample Input

3
1
10
1000

Sample Output

4.000000
3.041840
3.140593

Explanation

The 3 on the first line means three test cases follow.

The 1 on the second line means your generator should generate exactly the first term.

So the output of this test case should be 4.000000.

The 10 on the third line means your generator should generate exactly the first ten terms.

So the output of this test case should be 4 - 1.\overline{3} + 0.8 - ... = 3.041840.

Hint

generator


Comments


  • 1
    111006213  commented on May 12, 2023, 12:44 a.m. edited

    If the formula provided doesn't match the Sample Output. I find that using this formula gives out the correct answer:

    𝝅 = 4((-1 ^ i ) / (2( i +1)-1))


    • 1
      wadeyao  commented on May 13, 2023, 10:06 a.m.

      I've updated the formula. Thank you for your help.