Skip to main content

Exercise 4.3: polynomial-3.0.cpp

//polynomial-3.0.cpp

//Adapts polynomial-1.0.cpp to read coefficients from a
//file, and output linear solutions to one file and
//quadratic solutions to another.

//Simple program to solve polynomial equations up to 2nd order.
//Uses complex numbers for quadratic solutions.
//Steven Bamford

#include <cstdlib>
#include <iostream>
#include <cmath>
#include <complex>
#include <fstream>
#include <iomanip>
using namespace std;

int main()
{
  double a, b, c;  //coefficients of polynomial
                   //a*x*x + b*x + c = 0
  const double epsilon = 1.0e-300; //a few magnitudes
             //larger than the smallest double number

  ifstream fin;       //input data file stream
  ofstream fout_lin;  //ouput file stream for linear solutions
  ofstream fout_quad; //ouput file stream for quadratic solutions

  int width = 10;     //width of quad output fields 
  int precision = 6;  //precision of quad output values

  //open files
  fin.open("polynomial.in");
  fout_lin.open("lin_sol");
  fout_quad.open("quad_sol");

  //set file output formats
  fout_lin.setf(ios::fixed, ios::floatfield); //set format
  fout_lin.precision(precision);           //set precision
  fout_quad.setf(ios::fixed, ios::floatfield); //set format
  fout_quad.precision(precision);           //set precision

  //loop over data
  while (true)
    {
      fin >> a >> b >> c;  //read coeffs from file
      
      //break if end of file reached
      if (fin.eof()) break;

      if (abs(a) < epsilon)  //if a is zero
	{ //linear
	  double xr;   // one real solution
	  xr = -c/b;
	  fout_lin << setw(width) << xr << endl;
	}
      else //if a is non-zero
	{ //quadratic
	  complex<double> des;      //variable for the discriminant
	  complex<double> x1, x2;   //two complex solutions
	  des = b*b - 4*a*c;            //calc discriminant
	  x1 = (-b + sqrt(des))/(2*a);  //solution 1
	  x2 = (-b - sqrt(des))/(2*a);  //solution 2
	  //output in style from quadratic-5.0.cpp
	  fout_quad << "(" << setw(width) << x1.real() << ","
		    << setw(width) << x1.imag() << ") , " 
		    << "(" << setw(width) << x2.real() << "," 
		    << setw(width) << x2.imag() << ")" << endl;
	}
    }
  return(0);
}