C++ Bc. 7 cpp

Z GeoWikiCZ
Přejít na: navigace, hledání
#include <iostream>
#include <iomanip> // manipulatory (setw, setprecision, etc.)
#include <cmath>

double rada (double x, int& iter, double rel_chyba = 1e-8);

int main ()
{
  using namespace std;

  double x, xstd;
  int pocet_iteraci;

  const double krok = 0.2;

  for (double i = -1.0 + krok; i <= 1.0; i += krok)
    {
      x    = rada (i, pocet_iteraci);
      xstd = pow (sqrt(1 + i), -1);

      cout.setf (ios_base::fixed, ios_base::floatfield);
      // explicitne se uvadi znamenko '+'
      cout.setf (ios_base::showpos); 

      cout << setprecision(2) << setw ( 3) << i
	   << ' ' 
	   << setprecision(8) << setw (10) << x
	   << ' ' << xstd;

      cout.setf  (ios_base::scientific, ios_base::floatfield);
      cout.unsetf(ios_base::showpos);

      cout << ' ' << std::abs(x - xstd);

      cout.setf (ios_base::fixed);
      cout << ' ' << pocet_iteraci << endl;
    }
  
  return 0;
}

double rada ( double x , int& iter, double rel_chyba)
{
  double soucet = 1.0;
  double dif    = soucet;
  int    n      = 2;
  
  iter = 1;

  while (std::abs(dif) > rel_chyba * std::abs (soucet))
    {
      dif    *= -1.0 * ( (n - 1) * x ) / n ;
      n      += 2;
      soucet += dif;

      if ( iter == 1e+5 )
	{
	  break;
	}

      iter++;
    }

  return soucet;
}
-0.80 +2.23606789 +2.23606798 8.54408011e-08 68
-0.60 +1.58113881 +1.58113883 1.93443745e-08 32
-0.40 +1.29099444 +1.29099445 5.79704951e-09 19
-0.20 +1.11803399 +1.11803399 8.17512058e-10 12
-0.00 +1.00000000 +1.00000000 0.00000000e+00 2
+0.20 +0.91287093 +0.91287093 5.53753376e-10 12
+0.40 +0.84515425 +0.84515425 9.91450921e-10 20
+0.60 +0.79056941 +0.79056942 1.73567738e-09 34
+0.80 +0.74535600 +0.74535599 3.09478465e-09 73
+1.00 +0.70799884 +0.70710678 8.92058713e-04 100000

[ Zpět ]