CePP,
When I ran your code it produced the following output:
For 1.6439335666816
Do...while: 1.6439345666816
While: 1.6449340578302
Nacisnij klawisz, aby zakonczyc program... |
The correct answer to 6 decimal places is 1.644934. You can check this against the exact answer pi * pi / 6.
Your second answer - the Do ... while loop - does not give this answer to 6 d.p. accuracy; (it is actually out by about 0.001, an error in the 3rd decimal place). Your convergence criterion ensures only that one term is less than 0.000001 - it doesn't mean the answer is correct to 6 d.p. Your final answer seems sensible, however.
You may be interested in one famous series where this convergence criterion would fail spectacularly: the harmonic series
https://en.wikipedia.org/wiki/Harmonic_series_(mathematics) ; it is nominally zeta(1).
1/1 + 1/2 + 1/3 + 1/4 + 1/5 + ....
Even though individual terms tend to zero, the series does not actually converge. If you took a (very large) number of terms you could make the sum as big as you like. Another very famous hypothesis concerns the zeros of the zeta function for complex arguments. It is called the Riemann hypothesis (
https://en.wikipedia.org/wiki/Riemann_hypothesis ). If you were able to prove this you would bring yourself everlasting fame!
If you are interested in a general zeta function try the following. (Enter 2 when prompted. You can use the little "gear wheel" at the top-right of the code sample to run it.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double zeta;
double tolerance = 0.5e-6; // max error for 6 d.p. accuracy
double result = 0.0;
long n = 1;
cout << "Input zeta ( > 1 ): "; cin >> zeta;
while ( ( zeta - 1 ) / pow( n, zeta - 1 ) > tolerance ) // based on an integral bound for error
{
result += 1.0 / pow( n, zeta );
n++;
}
cout << "\nzeta(" << zeta << ") = " << setprecision(7) << result;
}
|