#+TITLE: Task 4b: Approximation of Pi: Sum 2
#+AUTHOR: JirR02

* Task

The number \(\pi\) can be defined through various infinite sums. The accuracy increases with the number of terms. Considering the following sum, which we call sum 2:

$$\frac{\pi}{2} = 1 + \sum_{j = 1}^{m - 1} \frac{\prod_{i=1}^j i}{\prod_{i=1}^j (2i + 1)} = 1 + \frac{1}{3} + \frac{1 \cdot 2}{3 \cdot 5} + \frac{1 \cdot 2 \cdot 3}{3 \cdot 5 \cdot 7} + ...$$

Write a program that computes and outputs an approximation of Pi, based on sum 2. The input for your program is the number of **terms** $m$ (including 1) to be included in the calculation to be done. The output is the approximation of \(\pi\).

**Optional**: After you have solved this and the previous task, think about which formula gives a more precise approximation of \(\pi\), sum 1 or sum 2 ? What are the drawbacks? Write your thoughts in a comment below the code.

* Input

A natural number \(m\) (\(m \geq 1\)).

* Output

The approximation of $\pi$ given by $m$ terms, rounded to 6 significant digits. Note that 6 significant digits is the default precision of C++ for printing floating-point values. Use a double variable to store the sum.

**Important**: the use of functions from the math library (e.g., =pow=) is prohibited.

* Solution

#+begin_src cpp
#include <iostream>

double productsumnum(double n) {
  double res = 1;
  for (int j = 1; j <= n; ++j) {
    res *= j;
  }
  return res;
}

double productsumden(double n) {
  double res = 1;
  for (int j = 1; j <= n; ++j) {
    res *= (2 * j + 1);
  }
  return res;
}

int main() {

  double m;      // User Input
  double pi = 2; // Pi
  float res;     // Outputed result with 6 significant digits

  std::cin >> m;

  for (int i = 1; i < m; ++i) {
    pi += (2 * (productsumnum(i) / productsumden(i)));
  }

  res = (float)(pi);
  std::cout << res;

  return 0;
}
#+end_src

-----

Made by JirR02 in Switzerland 🇨🇭
