Welcome to Project Lovelace! We're still in early development so there are still tons of bugs to find and improvements to make. If you have any suggestions, complaints, or comments please let us know on Discourse, Discord, or GitHub!

Almost π

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
 Function almost_pi(N)

You must be logged in to view your submissions.


How pi was almost 6.283185..., 3Blue1Brown


  • $\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. Would be nice if you don't post solutions in there but if you do then please organize and document your code well so others can learn from it.