horner.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /* Boost example/horner.cpp
  2. * example of unprotecting rounding for a whole function computation
  3. *
  4. * Copyright 2002-2003 Guillaume Melquiond
  5. *
  6. * Distributed under the Boost Software License, Version 1.0.
  7. * (See accompanying file LICENSE_1_0.txt or
  8. * copy at http://www.boost.org/LICENSE_1_0.txt)
  9. */
  10. #include <boost/numeric/interval.hpp>
  11. #include <iostream>
  12. // I is an interval class, the polynom is a simple array
  13. template<class I>
  14. I horner(const I& x, const I p[], int n) {
  15. // initialize and restore the rounding mode
  16. typename I::traits_type::rounding rnd;
  17. // define the unprotected version of the interval type
  18. typedef typename boost::numeric::interval_lib::unprotect<I>::type R;
  19. const R& a = x;
  20. R y = p[n - 1];
  21. for(int i = n - 2; i >= 0; i--) {
  22. y = y * a + (const R&)(p[i]);
  23. }
  24. return y;
  25. // restore the rounding mode with the destruction of rnd
  26. }
  27. template<class T, class Policies>
  28. std::ostream &operator<<(std::ostream &os,
  29. const boost::numeric::interval<T, Policies> &x) {
  30. os << "[" << x.lower() << ", " << x.upper() << "]";
  31. return os;
  32. }
  33. int main() {
  34. typedef boost::numeric::interval<double> I;
  35. I p[3] = { -1.0, 0, 1.0 };
  36. I x = 1.0;
  37. std::cout << horner(x, p, 3) << std::endl;
  38. return 0;
  39. }