Compile time math utilities
[sol.git] / sol / math / ratio.hpp
blobc8fd60486b5934f38a56088b90ffa30fb6325b46
1 #if !defined(sol_math_ratio_hpp_included)
2 #define sol_math_ratio_hpp_included
3 /// \addtogroup sol_math
4 /// \{
7 /**
8 * \file sol/math/ratio.hpp
9 * \brief Compute rational values at compile time
11 * \see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm#ratio
13 * \todo ratio comparison
17 #include <sol/cstdint.hpp>
18 #include <sol/math/abs.hpp>
19 #include <sol/math/gcd.hpp>
20 #include <sol/math/sign.hpp>
21 #include <sol/static_assert.hpp>
24 namespace sol { namespace math {
27 /// Rational value representation (calculated during compile-time)
28 template <intmax_t N, intmax_t D=1>
29 class ratio
31 private:
33 static_assert(D != 0, "D != 0");
35 public:
37 /// numerator
38 static intmax_t const num = N * sign<D>::value / gcd<N, D>::value;
40 /// denominator
41 static intmax_t const den = abs<D>::value / gcd<N, D>::value;
45 /// rational arithmetic: addition
46 template <typename R1, typename R2>
47 struct ratio_add
49 /// resulting type
50 typedef ratio<
51 R1::num * R2::den + R2::num * R1::den
52 , R1::den * R2::den
53 > type;
57 /// rational arithmetic: subtraction
58 template <typename R1, typename R2>
59 struct ratio_subtract
61 /// resulting type
62 typedef ratio<
63 R1::num * R2::den - R2::num * R1::den
64 , R1::den * R2::den
65 > type;
69 /// rational arithmetic: multiplication
70 template <typename R1, typename R2>
71 struct ratio_multiply
73 /// resulting type
74 typedef ratio<
75 R1::num * R2::num
76 , R1::den * R2::den
77 > type;
81 /// rational arithmetic: division
82 template <typename R1, typename R2>
83 struct ratio_divide
85 /// resulting type
86 typedef ratio<
87 R1::num * R2::den
88 , R1::den * R2::num
89 > type;
93 /// Convenience SI units
94 /// \{
95 typedef ratio<1, 1000000000000000000> atto;
96 typedef ratio<1, 1000000000000000> femto;
97 typedef ratio<1, 1000000000000> pico;
98 typedef ratio<1, 1000000000> nano;
99 typedef ratio<1, 1000000> micro;
100 typedef ratio<1, 1000> milli;
101 typedef ratio<1, 100> centi;
102 typedef ratio<1, 10> deci;
103 typedef ratio< 10, 1> deca;
104 typedef ratio< 100, 1> hecto;
105 typedef ratio< 1000, 1> kilo;
106 typedef ratio< 1000000, 1> mega;
107 typedef ratio< 1000000000, 1> giga;
108 typedef ratio< 1000000000000, 1> tera;
109 typedef ratio< 1000000000000000, 1> peta;
110 typedef ratio<1000000000000000000, 1> exa;
111 /// \}
114 }} // namespace sol::math
117 /// \}
118 #endif // sol_math_ratio_hpp_included