rational_adaptor.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. ///////////////////////////////////////////////////////////////
  2. // Copyright 2011 John Maddock. Distributed under the Boost
  3. // Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt
  5. #ifndef BOOST_MATH_RATIONAL_ADAPTER_HPP
  6. #define BOOST_MATH_RATIONAL_ADAPTER_HPP
  7. #include <iostream>
  8. #include <iomanip>
  9. #include <sstream>
  10. #include <cstdint>
  11. #include <boost/functional/hash_fwd.hpp>
  12. #include <boost/multiprecision/number.hpp>
  13. #ifdef BOOST_MSVC
  14. #pragma warning(push)
  15. #pragma warning(disable : 4512 4127)
  16. #endif
  17. #include <boost/rational.hpp>
  18. #ifdef BOOST_MSVC
  19. #pragma warning(pop)
  20. #endif
  21. namespace boost {
  22. namespace multiprecision {
  23. namespace backends {
  24. template <class IntBackend>
  25. struct rational_adaptor
  26. {
  27. using integer_type = number<IntBackend> ;
  28. using rational_type = boost::rational<integer_type>;
  29. using signed_types = typename IntBackend::signed_types ;
  30. using unsigned_types = typename IntBackend::unsigned_types;
  31. using float_types = typename IntBackend::float_types ;
  32. rational_adaptor() noexcept(noexcept(rational_type())) {}
  33. rational_adaptor(const rational_adaptor& o) noexcept(noexcept(std::declval<rational_type&>() = std::declval<const rational_type&>()))
  34. {
  35. m_value = o.m_value;
  36. }
  37. rational_adaptor(const IntBackend& o) noexcept(noexcept(rational_type(std::declval<const IntBackend&>()))) : m_value(o) {}
  38. template <class U>
  39. rational_adaptor(const U& u, typename std::enable_if<std::is_convertible<U, IntBackend>::value>::type* = 0)
  40. : m_value(static_cast<integer_type>(u)) {}
  41. template <class U>
  42. explicit rational_adaptor(const U& u,
  43. typename std::enable_if<
  44. boost::multiprecision::detail::is_explicitly_convertible<U, IntBackend>::value && !std::is_convertible<U, IntBackend>::value>::type* = 0)
  45. : m_value(IntBackend(u)) {}
  46. template <class U>
  47. typename std::enable_if<(boost::multiprecision::detail::is_explicitly_convertible<U, IntBackend>::value && !boost::multiprecision::detail::is_arithmetic<U>::value), rational_adaptor&>::type operator=(const U& u)
  48. {
  49. m_value = IntBackend(u);
  50. return *this;
  51. }
  52. // rvalues:
  53. rational_adaptor(rational_adaptor&& o) noexcept(noexcept(rational_type(std::declval<rational_type>()))) : m_value(static_cast<rational_type&&>(o.m_value))
  54. {}
  55. rational_adaptor(IntBackend&& o) noexcept(noexcept(rational_type(std::declval<IntBackend>()))) : m_value(static_cast<IntBackend&&>(o)) {}
  56. rational_adaptor& operator=(rational_adaptor&& o) noexcept(noexcept(std::declval<rational_type&>() = std::declval<rational_type>()))
  57. {
  58. m_value = static_cast<rational_type&&>(o.m_value);
  59. return *this;
  60. }
  61. rational_adaptor& operator=(const rational_adaptor& o)
  62. {
  63. m_value = o.m_value;
  64. return *this;
  65. }
  66. rational_adaptor& operator=(const IntBackend& o)
  67. {
  68. m_value = o;
  69. return *this;
  70. }
  71. template <class Int>
  72. typename std::enable_if<boost::multiprecision::detail::is_integral<Int>::value, rational_adaptor&>::type operator=(Int i)
  73. {
  74. m_value = i;
  75. return *this;
  76. }
  77. template <class Float>
  78. typename std::enable_if<std::is_floating_point<Float>::value, rational_adaptor&>::type operator=(Float i)
  79. {
  80. int e;
  81. Float f = std::frexp(i, &e);
  82. f = std::ldexp(f, std::numeric_limits<Float>::digits);
  83. e -= std::numeric_limits<Float>::digits;
  84. integer_type num(f);
  85. integer_type denom(1u);
  86. if (e > 0)
  87. {
  88. num <<= e;
  89. }
  90. else if (e < 0)
  91. {
  92. denom <<= -e;
  93. }
  94. m_value.assign(num, denom);
  95. return *this;
  96. }
  97. rational_adaptor& operator=(const char* s)
  98. {
  99. std::string s1;
  100. multiprecision::number<IntBackend> v1, v2;
  101. char c;
  102. bool have_hex = false;
  103. const char* p = s; // saved for later
  104. while ((0 != (c = *s)) && (c == 'x' || c == 'X' || c == '-' || c == '+' || (c >= '0' && c <= '9') || (have_hex && (c >= 'a' && c <= 'f')) || (have_hex && (c >= 'A' && c <= 'F'))))
  105. {
  106. if (c == 'x' || c == 'X')
  107. have_hex = true;
  108. s1.append(1, c);
  109. ++s;
  110. }
  111. v1.assign(s1);
  112. s1.erase();
  113. if (c == '/')
  114. {
  115. ++s;
  116. while ((0 != (c = *s)) && (c == 'x' || c == 'X' || c == '-' || c == '+' || (c >= '0' && c <= '9') || (have_hex && (c >= 'a' && c <= 'f')) || (have_hex && (c >= 'A' && c <= 'F'))))
  117. {
  118. if (c == 'x' || c == 'X')
  119. have_hex = true;
  120. s1.append(1, c);
  121. ++s;
  122. }
  123. v2.assign(s1);
  124. }
  125. else
  126. v2 = 1;
  127. if (*s)
  128. {
  129. BOOST_THROW_EXCEPTION(std::runtime_error(std::string("Could not parse the string \"") + p + std::string("\" as a valid rational number.")));
  130. }
  131. data().assign(v1, v2);
  132. return *this;
  133. }
  134. void swap(rational_adaptor& o)
  135. {
  136. std::swap(m_value, o.m_value);
  137. }
  138. std::string str(std::streamsize digits, std::ios_base::fmtflags f) const
  139. {
  140. //
  141. // We format the string ourselves so we can match what GMP's mpq type does:
  142. //
  143. std::string result = data().numerator().str(digits, f);
  144. if (data().denominator() != 1)
  145. {
  146. result.append(1, '/');
  147. result.append(data().denominator().str(digits, f));
  148. }
  149. return result;
  150. }
  151. void negate()
  152. {
  153. m_value = -m_value;
  154. }
  155. int compare(const rational_adaptor& o) const
  156. {
  157. return m_value > o.m_value ? 1 : (m_value < o.m_value ? -1 : 0);
  158. }
  159. template <class Arithmatic>
  160. typename std::enable_if<boost::multiprecision::detail::is_arithmetic<Arithmatic>::value && !std::is_floating_point<Arithmatic>::value, int>::type compare(Arithmatic i) const
  161. {
  162. return m_value > i ? 1 : (m_value < i ? -1 : 0);
  163. }
  164. template <class Arithmatic>
  165. typename std::enable_if<std::is_floating_point<Arithmatic>::value, int>::type compare(Arithmatic i) const
  166. {
  167. rational_adaptor r;
  168. r = i;
  169. return this->compare(r);
  170. }
  171. rational_type& data() { return m_value; }
  172. const rational_type& data() const { return m_value; }
  173. template <class Archive>
  174. void serialize(Archive& ar, const std::integral_constant<bool, true>&)
  175. {
  176. // Saving
  177. integer_type n(m_value.numerator()), d(m_value.denominator());
  178. ar& boost::make_nvp("numerator", n);
  179. ar& boost::make_nvp("denominator", d);
  180. }
  181. template <class Archive>
  182. void serialize(Archive& ar, const std::integral_constant<bool, false>&)
  183. {
  184. // Loading
  185. integer_type n, d;
  186. ar& boost::make_nvp("numerator", n);
  187. ar& boost::make_nvp("denominator", d);
  188. m_value.assign(n, d);
  189. }
  190. template <class Archive>
  191. void serialize(Archive& ar, const unsigned int /*version*/)
  192. {
  193. using tag = typename Archive::is_saving;
  194. using saving_tag = std::integral_constant<bool, tag::value>;
  195. serialize(ar, saving_tag());
  196. }
  197. private:
  198. rational_type m_value;
  199. };
  200. template <class IntBackend>
  201. inline void eval_add(rational_adaptor<IntBackend>& result, const rational_adaptor<IntBackend>& o)
  202. {
  203. result.data() += o.data();
  204. }
  205. template <class IntBackend>
  206. inline void eval_subtract(rational_adaptor<IntBackend>& result, const rational_adaptor<IntBackend>& o)
  207. {
  208. result.data() -= o.data();
  209. }
  210. template <class IntBackend>
  211. inline void eval_multiply(rational_adaptor<IntBackend>& result, const rational_adaptor<IntBackend>& o)
  212. {
  213. result.data() *= o.data();
  214. }
  215. template <class IntBackend>
  216. inline void eval_divide(rational_adaptor<IntBackend>& result, const rational_adaptor<IntBackend>& o)
  217. {
  218. using default_ops::eval_is_zero;
  219. if (eval_is_zero(o))
  220. {
  221. BOOST_THROW_EXCEPTION(std::overflow_error("Divide by zero."));
  222. }
  223. result.data() /= o.data();
  224. }
  225. template <class R, class IntBackend>
  226. inline typename std::enable_if<number_category<R>::value == number_kind_floating_point>::type eval_convert_to(R* result, const rational_adaptor<IntBackend>& backend)
  227. {
  228. //
  229. // The generic conversion is as good as anything we can write here:
  230. //
  231. ::boost::multiprecision::detail::generic_convert_rational_to_float(*result, backend);
  232. }
  233. template <class R, class IntBackend>
  234. inline typename std::enable_if<(number_category<R>::value != number_kind_integer) && (number_category<R>::value != number_kind_floating_point)>::type eval_convert_to(R* result, const rational_adaptor<IntBackend>& backend)
  235. {
  236. using comp_t = typename component_type<number<rational_adaptor<IntBackend> > >::type;
  237. comp_t num(backend.data().numerator());
  238. comp_t denom(backend.data().denominator());
  239. *result = num.template convert_to<R>();
  240. *result /= denom.template convert_to<R>();
  241. }
  242. template <class R, class IntBackend>
  243. inline typename std::enable_if<number_category<R>::value == number_kind_integer>::type eval_convert_to(R* result, const rational_adaptor<IntBackend>& backend)
  244. {
  245. using comp_t = typename component_type<number<rational_adaptor<IntBackend> > >::type;
  246. comp_t t = backend.data().numerator();
  247. t /= backend.data().denominator();
  248. *result = t.template convert_to<R>();
  249. }
  250. template <class IntBackend>
  251. inline bool eval_is_zero(const rational_adaptor<IntBackend>& val)
  252. {
  253. using default_ops::eval_is_zero;
  254. return eval_is_zero(val.data().numerator().backend());
  255. }
  256. template <class IntBackend>
  257. inline int eval_get_sign(const rational_adaptor<IntBackend>& val)
  258. {
  259. using default_ops::eval_get_sign;
  260. return eval_get_sign(val.data().numerator().backend());
  261. }
  262. template <class IntBackend, class V>
  263. inline void assign_components(rational_adaptor<IntBackend>& result, const V& v1, const V& v2)
  264. {
  265. result.data().assign(v1, v2);
  266. }
  267. template <class IntBackend>
  268. inline std::size_t hash_value(const rational_adaptor<IntBackend>& val)
  269. {
  270. std::size_t result = hash_value(val.data().numerator());
  271. boost::hash_combine(result, val.data().denominator());
  272. return result;
  273. }
  274. } // namespace backends
  275. template <class IntBackend>
  276. struct expression_template_default<backends::rational_adaptor<IntBackend> > : public expression_template_default<IntBackend>
  277. {};
  278. template <class IntBackend>
  279. struct number_category<backends::rational_adaptor<IntBackend> > : public std::integral_constant<int, number_kind_rational>
  280. {};
  281. using boost::multiprecision::backends::rational_adaptor;
  282. template <class Backend, expression_template_option ExpressionTemplates>
  283. struct component_type<number<backends::rational_adaptor<Backend>, ExpressionTemplates> >
  284. {
  285. using type = number<Backend, ExpressionTemplates>;
  286. };
  287. template <class IntBackend, expression_template_option ET>
  288. inline number<IntBackend, ET> numerator(const number<rational_adaptor<IntBackend>, ET>& val)
  289. {
  290. return val.backend().data().numerator();
  291. }
  292. template <class IntBackend, expression_template_option ET>
  293. inline number<IntBackend, ET> denominator(const number<rational_adaptor<IntBackend>, ET>& val)
  294. {
  295. return val.backend().data().denominator();
  296. }
  297. }} // namespace boost::multiprecision
  298. namespace std {
  299. template <class IntBackend, boost::multiprecision::expression_template_option ExpressionTemplates>
  300. class numeric_limits<boost::multiprecision::number<boost::multiprecision::rational_adaptor<IntBackend>, ExpressionTemplates> > : public std::numeric_limits<boost::multiprecision::number<IntBackend, ExpressionTemplates> >
  301. {
  302. using base_type = std::numeric_limits<boost::multiprecision::number<IntBackend> > ;
  303. using number_type = boost::multiprecision::number<boost::multiprecision::rational_adaptor<IntBackend> >;
  304. public:
  305. static constexpr bool is_integer = false;
  306. static constexpr bool is_exact = true;
  307. static constexpr number_type(min)() { return (base_type::min)(); }
  308. static constexpr number_type(max)() { return (base_type::max)(); }
  309. static constexpr number_type lowest() { return -(max)(); }
  310. static constexpr number_type epsilon() { return base_type::epsilon(); }
  311. static constexpr number_type round_error() { return epsilon() / 2; }
  312. static constexpr number_type infinity() { return base_type::infinity(); }
  313. static constexpr number_type quiet_NaN() { return base_type::quiet_NaN(); }
  314. static constexpr number_type signaling_NaN() { return base_type::signaling_NaN(); }
  315. static constexpr number_type denorm_min() { return base_type::denorm_min(); }
  316. };
  317. template <class IntBackend, boost::multiprecision::expression_template_option ExpressionTemplates>
  318. constexpr bool numeric_limits<boost::multiprecision::number<boost::multiprecision::rational_adaptor<IntBackend>, ExpressionTemplates> >::is_integer;
  319. template <class IntBackend, boost::multiprecision::expression_template_option ExpressionTemplates>
  320. constexpr bool numeric_limits<boost::multiprecision::number<boost::multiprecision::rational_adaptor<IntBackend>, ExpressionTemplates> >::is_exact;
  321. } // namespace std
  322. #endif