C++ Bc. 9 cpp

Z GeoWikiCZ
Přejít na: navigace, hledání
#include <iostream>
#include <iomanip>
#include <cmath>

struct Chyba
{
   Chyba(std::string t) : text(t) {}

   std::string text;
};

double maclaurin (double x, double a, int& iter, double rel_chyba = 1e-12);

int main ()
{
  using namespace std;

  double m, mstd;
  int    pocet_iteraci;

  for (double x = -1.20; x <= 1.21; x += 0.4)
    {
      for (double a = -2; a <= 2; a++)
	{
	  try
	    {
	      cout.setf (ios_base::fixed, ios_base::floatfield);
	      // explicitne se uvadi znamenko '+'
	      cout.setf (ios_base::showpos); 
	      
	      cout << setprecision(2) << setw (3) << x
		   << ' ' << setw(3) << a
		   << ' ';

	      m    = maclaurin (x, a, pocet_iteraci);
	      mstd = pow (1 + x, a);

	      cout << setprecision( 6) << setw (10) << m
		   << ' ' << setw (10) << mstd;
	      
	      cout.setf  (ios_base::scientific, ios_base::floatfield);
	      cout.unsetf(ios_base::showpos);
	      
	      cout << ' ' << std::abs(m - mstd);
	      
	      cout.setf (ios_base::fixed);
	      cout << ' ' << pocet_iteraci << endl;
	    }
	  catch (Chyba& err)
	    {
	      cout << err.text << endl;
	    }
	}
      for (int i = 0; i < 72; i++)
	{
	  cout << "-";
	}
      cout << endl;
    }

  return 0;
}

double maclaurin (double x, double a, int& iter, double rel_chyba)
{
  if ( std::abs(x) >= 1.0 && !(int(a) == a && a>=0))
    {
      throw Chyba (" ...");
    }
  
  double dif      = a * x;
  double vysledek = 1.0 + dif;
  int    n        = 2;
  
  while (std::abs (dif) > std::abs (vysledek*rel_chyba))
    {
      dif      *= x * (a - (n - 1)) / n;
      vysledek += dif;
      n++;
    }

  iter = n;

  return vysledek;
}

[ Zpět ]