1 // (C) Copyright John Maddock 2015.
2 // Use, modification and distribution are subject to the
3 // Boost Software License, Version 1.0. (See accompanying file
4 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 #ifndef BOOST_MATH_SPECIAL_ULP_HPP
7 #define BOOST_MATH_SPECIAL_ULP_HPP
13 #include <boost/math/special_functions/math_fwd.hpp>
14 #include <boost/math/policies/error_handling.hpp>
15 #include <boost/math/special_functions/fpclassify.hpp>
16 #include <boost/math/special_functions/next.hpp>
18 namespace boost{ namespace math{ namespace detail{
20 template <class T, class Policy>
21 T ulp_imp(const T& val, const Policy& pol)
25 static const char* function = "ulp<%1%>(%1%)";
27 int fpclass = (boost::math::fpclassify)(val);
29 if(fpclass == (int)FP_NAN)
31 return policies::raise_domain_error<T>(
33 "Argument must be finite, but got %1%", val, pol);
35 else if((fpclass == (int)FP_INFINITE) || (fabs(val) >= tools::max_value<T>()))
37 return (val < 0 ? -1 : 1) * policies::raise_overflow_error<T>(function, 0, pol);
39 else if(fpclass == FP_ZERO)
40 return detail::get_smallest_value<T>();
42 // This code is almost the same as that for float_next, except for negative integers,
43 // where we preserve the relation ulp(x) == ulp(-x) as does Java:
45 frexp(fabs(val), &expon);
46 T diff = ldexp(T(1), expon - tools::digits<T>());
48 diff = detail::get_smallest_value<T>();
54 template <class T, class Policy>
55 inline typename tools::promote_args<T>::type ulp(const T& val, const Policy& pol)
57 typedef typename tools::promote_args<T>::type result_type;
58 return detail::ulp_imp(static_cast<result_type>(val), pol);
62 inline typename tools::promote_args<T>::type ulp(const T& val)
64 return ulp(val, policies::policy<>());
70 #endif // BOOST_MATH_SPECIAL_ULP_HPP