Example 1
Input: 25
Output: 3.1815766854350325
Almost $\pi$
You will learn about: loops, summation, and 🥧.
The number $\pi$=3.1415926535897... is the ratio of a circle's circumference to its diameter and shows basically everywhere in math and science. It's like the most famous number in math. It's decimal expansion goes on forever but we can actually calculate it by summing up a bunch of fractions $$ \frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} - \frac{1}{11} + \dots = \sum_{k=0}^\infty \frac{(-1)^k}{2k+1} $$ By adding more and more terms, you get a better and better approximation to $\pi$. Of course, you can keep summing an infinite number of terms so in practice you cut it off after $n$ terms. Given the number of terms $n$, sum the first $n$ terms and return the result. Remember the $k=0$ term (equal to 1) counts as the first term.
Input: An integer $n$ for the number of terms to sum in calculating $\pi$ using the above equation.
Output: The sum of the first $n$ terms giving an approximation to $\pi$.
Difficulty | Timesink | ||
---|---|---|---|
Maximum runtime | 60 s | Max. memory usage | 250 MiB |
Function signature | almost_pi(N) |
Write a function that accepts the input as function parameters and returns the correct output. Make sure to read the description above to produce the correct output in the correct format and use the correct function signature so we can run your code. A good first step is to try reproducing the example(s). Your code must not take longer than the maximum runtime to run and must not use more memory than the allowed limit.
You must be logged in to view your submissions.
Let us know what you think about this problem! Was it too hard? Difficult to understand? Also feel free to discuss the problem, ask questions, and post cool stuff on Discourse. You should be able see a discussion thread below. Feel free to post your solutions but if you do please organize and document your code well so others can learn from it.