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 that x^0
is 1 (if x \neq 0
).
Important: the use of functions from the math library (e.g., pow) is prohibited.