// $Id$ #ifndef _utl_Polynomial_h_ #define _utl_Polynomial_h_ #include #include #include #include namespace utl { /** \class Polynomial \brief Simple polynomial container Implements numerically stable Horner evaluation. \author Darko Veberic \date 29 Oct 2014 */ class Polynomial : public SafeBoolCast { public: Polynomial(const double coeff = 0) : fCoeff(1, coeff) { } Polynomial(const std::vector& coeff) : fCoeff(coeff) { Check(); } template Polynomial(const T (&coeff)[n]) : fCoeff(coeff, coeff + n) { Check(); } double operator()(const double x) const { std::vector::const_reverse_iterator it = fCoeff.rbegin(); double sum = *it++; for (std::vector::const_reverse_iterator end = fCoeff.rend(); it != end; ++it) sum = *it + x * sum; return sum; } const std::vector& GetCoefficients() const { return fCoeff; } bool IsZero() const { for (std::vector::const_iterator it = fCoeff.begin(), end = fCoeff.end(); it != end; ++it) if (*it) return false; return true; } bool BoolCast() const { return !IsZero(); } private: void Check() const { if (fCoeff.empty()) throw DoesNotComputeException("Polynomial should have at least one coefficient!"); } std::vector fCoeff; }; std::istream& operator>>(std::istream& is, Polynomial& p); std::ostream& operator<<(std::ostream& is, const Polynomial& p); } #endif