C++ Bc. 21 cpp

Z GeoWikiCZ
#include <iostream>
#include <cmath>

double odmocnina(double);
void   tabulka(std::ostream&, double (*f)(double));

int main()
{
  tabulka(std::cout, &odmocnina);

  double arg = 0, maxdif = 0;
  for (double x=0; x<=1; x+=0.01)
    {
      double dif = std::sqrt(x) - odmocnina(x);
      if (std::abs(dif) > std::abs(maxdif))
      {
	maxdif = dif;
	arg = x;
      }
    }

  using namespace std;
  cout.setf(ios_base::scientific, ios_base::floatfield);
  cout.precision(2);

  cout << "\nMaximalni chyba na intervalu <0,1) je " << maxdif;
  if (maxdif) 
    {
      cout.setf(ios_base::fixed, ios_base::floatfield);
      cout << " pro argument " << arg;
    }
  cout << "\n";
}


double odmocnina(double x)
{
  if (x == 0) return 0;

  const double tolerance = 1e-7;
  double g, f = x;
  do 
    {
      g = f;
      f = 0.5*(f + x/f);
    }
  while (std::abs(g - f)/f > tolerance);

  return f;
}


void tabulka(std::ostream& out, double (*f)(double))
{
  using namespace std;
  const int parg = 1;   // presnost zobrazeni argumentu
  const int pfun = 4;   // presnost zobrazeni funkcnich hodnot

  out << "+-----+------------------------------------+\n";
  out << "|  x  |    0      2      4      6      8   |\n";
  out << "+-----+------------------------------------+\n";

  out.setf(ios_base::fixed, ios_base::floatfield);
  for (double x=0; x<0.99; x+= 0.1)
    {
      out.precision(parg);
      out << "| " << x << " | ";

      out.precision(pfun);
      for (double dx=0; dx<0.1; dx+= 0.02)
	{
	  out << f(x+dx) << " ";
	}

      out << "|\n";
    }

  out << "+-----+------------------------------------+\n";
}

[ Zpět ]