CommencerCommencer gratuitement

Approximate Pi with recursion

The number \(\pi\) can be computed by the following formula: $$ \pi = 4\sum_{k=0}^{\infty}\frac{(-1)^k}{2k+1}=4\left(\frac{1}{1}-\frac{1}{3}+\frac{1}{5}-\frac{1}{7}+\frac{1}{9}-…\right) $$ Your task is to write a recursive function to approximate \(\pi\) using the formula defined above (the approximation means that instead of infinity \(\infty\), the sequence considers only a certain amount of elements \(n\)).

Here are examples of \(\pi\) for some of the values of \(n\):
\(n=0 \rightarrow \pi = 4\)
\(n=1 \rightarrow \pi \approx 2.67\)
\(n=2 \rightarrow \pi \approx 3.47\)

Cet exercice fait partie du cours

Practicing Coding Interview Questions in Python

Afficher le cours

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

# Write an expression to get the k-th element of the series
get_elmnt = lambda k: ____/____
Modifier et exécuter le code