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
11 #include <boost/numeric/interval.hpp>
12 #include <iostream>
13
14 // I is an interval class, the polynom is a simple array
15 template<class I>
horner(const I & x,const I p[],int n)16 I horner(const I& x, const I p[], int n) {
17
18 // initialize and restore the rounding mode
19 typename I::traits_type::rounding rnd;
20
21 // define the unprotected version of the interval type
22 typedef typename boost::numeric::interval_lib::unprotect<I>::type R;
23
24 const R& a = x;
25 R y = p[n - 1];
26 for(int i = n - 2; i >= 0; i--) {
27 y = y * a + (const R&)(p[i]);
28 }
29 return y;
30
31 // restore the rounding mode with the destruction of rnd
32 }
33
34 template<class T, class Policies>
operator <<(std::ostream & os,const boost::numeric::interval<T,Policies> & x)35 std::ostream &operator<<(std::ostream &os,
36 const boost::numeric::interval<T, Policies> &x) {
37 os << "[" << x.lower() << ", " << x.upper() << "]";
38 return os;
39 }
40
main()41 int main() {
42 typedef boost::numeric::interval<double> I;
43 I p[3] = { -1.0, 0, 1.0 };
44 I x = 1.0;
45 std::cout << horner(x, p, 3) << std::endl;
46 return 0;
47 }
48