carl  24.04
Computer ARithmetic Library
generic.h
Go to the documentation of this file.
1 #pragma once
2 
3 namespace carl {
4 
5 /**
6  * Returns a down-rounded representation of the given numeric.
7  * @param o Number to round.
8  * @param overapproximate Flag if overapproximation shall be guaranteed.
9  * @return Double representation of o.
10  */
11 template<typename Rational>
12 double roundDown(const Rational& o, bool overapproximate = false) {
13  using limits = std::numeric_limits<double>;
14  double result = carl::to_double(o);
15  if (result == -limits::infinity()) {
16  return result;
17  }
18  if (result == limits::infinity()) {
19  return limits::max();
20  }
21  // If the cln::cl_RA cannot be represented exactly by a double, round.
22  if (overapproximate || carl::rationalize<Rational>(result) != o) {
23  if (result == -limits::max()) {
24  return -limits::infinity();
25  }
26  return std::nextafter(result, -limits::infinity());
27  } else {
28  return result;
29  }
30 }
31 
32 /** Returns a up-rounded representation of the given numeric
33  * @param o
34  * @param overapproximate
35  * @return double representation of o (overapprox) Note, that it can return the double INFINITY.
36  */
37 template<typename Rational>
38 double roundUp(const Rational& o, bool overapproximate = false) {
39  using limits = std::numeric_limits<double>;
40  double result = carl::to_double(o);
41  if (result == limits::infinity()) {
42  return result;
43  }
44  if (result == -limits::infinity()) {
45  return -limits::max();
46  }
47  // If the cln::cl_RA cannot be represented exactly by a double, round.
48  if (overapproximate || carl::rationalize<Rational>(result) != o) {
49  if (result == limits::max()) {
50  return limits::infinity();
51  }
52  return std::nextafter(result, limits::infinity());
53  } else {
54  return result;
55  }
56 }
57 } // namespace carl
mpq_class Rational
Definition: HornerTest.cpp:12
carl is the main namespace for the library.
double roundDown(const Rational &o, bool overapproximate=false)
Returns a down-rounded representation of the given numeric.
Definition: generic.h:12
double roundUp(const Rational &o, bool overapproximate=false)
Returns a up-rounded representation of the given numeric.
Definition: generic.h:38
double to_double(const cln::cl_RA &n)
Converts the given fraction to a double.
Definition: operations.h:113