// Reihe.cc // // Sum 1/kČ = Pi^2 / 6 [Euler, 1736] // limited accuracy // Is s1 or s2 closer to right result ? #include #include #include main() { float s1,s2; int i,n ; cout << endl << "Demo for precision of float" << endl; // Print the index where cancelation has to be expected for float cout << "The first sum will be rather precise until n = " << ceil(sqrt(1./FLT_EPSILON)) << endl; // Input highest index cout << endl << " n = "; cin >> n; // n = 65000; // Calculate in incrementing order s1 = 0.0; for (i=1; i<=n; i++) { s1 += 1.0/i/i; } cout << endl << "s1 = " << s1 << endl << endl; // Calculate in decrementing order s2 = 0.0; for (i=n; i>=1; i--) { s2 += 1.0/i/i; // s2 += 1.0/(i*i); // results in inf // since i*i may be longer than int supports } cout << endl << "s2 = " << s2 << endl << endl; // Compare both sums cout << endl << "Diff " << s2-s1 << endl << endl; // Compare sums with exact result cout << endl << "Pi*Pi/6 - s1 : " << M_PI*M_PI/6-s1 << endl; cout << endl << "Pi*Pi/6 - s2 : " << M_PI*M_PI/6-s2 << endl << endl; }