Welcome to Project Lovelace! We're still super new so there are still tons of bugs to find and improvements to make. If you have any suggestions, complaints, or any comments at all please let us know on Discourse!

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.


The blue line shows the sum of the first $n$ terms for $0 \le n \le 50$ while the orange dashed line shows the exact value of $\pi$. By adding each term, you end up overestimating then underestimating $\pi$, but it slowly converges to the exact value.


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$.


Example 1

Input: 25 Output: 3.1815766854350325

Example 2

Input: 10000 Output: 3.1414926535900345


 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.

Videos

How pi was almost 6.283185..., 3Blue1Brown

Notes

  • $\pi$ is a transcendental number and its digital expansion contains all possible numbers. 123456789 first shows up at the 523,551,502nd decimal place! You can search through the first billion digits at A Billion Digits of Pi.

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.