JirR02 88e0b5ed69 Converted everything to orgmode
converted everything to orgmode and added solution to the README files
2025-03-31 08:40:43 +02:00
..
2025-03-31 08:40:43 +02:00

Task 4a: Approximation of Pi: Sum 1

Task

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

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

Note that \(m\) is the number of the terms in the sum. For example, \(m=2\)$ refers to the sum of the terms \(1\) (for \(j=0\)) and \(-\frac{1}{3}\) (for \(j=1\)). This examples yields a value of \(4 \cdot (1-\frac{1}{3})\) for \(\pi\).

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

Input

A number \(m \geq 1\).

Output

The approximation of \(\pi\) given by \(4 \sum_{j=0}^{m-1} \frac{(-1)^j}{2j + 1}\), rounded to 6 significant digits. Note that 6 significant digits is the default precision of C++ for printing floating-point values. Use a variable of type double to calculate the sum. Note that \(x^0\) is 1 (if \(x \neq 0\)).

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

Solution

#include <iostream>

double power(double n, double e) { // Self defined function for exponent
  int res = 1;
  for (; e > 0; --e) {
    res *= n;
  }
  return res;
}

int main() {
  double m;      // User Input
  double pi = 0; // Pi
  float res;     // Outputed result with 6 significant digits

  std::cin >> m;

  if (m < 1) { // Check if Input is greater than 1.
    return 0;
  } else {
    for (int i = 0; i < m; ++i) {
      pi = pi + 4 * ((power(-1, i)) / ((2 * i) + 1)); // calculate Pi
    }

    res = (float)(pi); // round to 6 significant digits
    std::cout << res;

    return 0;
  }
}

Made by JirR02 in Switzerland 🇨🇭