]> git.donarmstrong.com Git - lilypond.git/blob - flower/include/rational.hh
969d0121470db512f58f342046fd5293c735ad29
[lilypond.git] / flower / include / rational.hh
1 /*
2   rational.hh -- declare rational helpers
3
4   source file of the Flower Library
5
6   (c) 1997--2007 Han-Wen Nienhuys <hanwen@xs4all.nl>
7 */
8
9 #ifndef RATIONAL_HH
10 #define RATIONAL_HH
11
12 #include "std-string.hh"
13 #include <limits.h>
14
15 /**
16    Rational numbers.  Included is support for + and - infinity.
17 */
18 class Rational
19 {
20   /**
21      Sign of rational.
22      -2, .. 2
23
24      -2,2 is - and + infinity.
25      -1,1 is negative and positive.
26      0 if *this is zero.
27   */
28   int sign_;
29   unsigned int num_, den_;
30   void normalize ();
31   void copy (Rational const &);
32
33 public:
34   void set_infinite (int sign);
35   bool is_infinity () const;
36   void invert ();
37   int numerator () const { return sign_ * num_; }
38   int denominator () const { return den_; }
39   int num () const { return numerator (); }
40   int den () const { return denominator (); }
41
42   Rational trunc_rat () const;
43   Rational div_rat (Rational) const;
44   Rational mod_rat (Rational) const;
45   Rational abs () const;
46   void negate ();
47   int to_int () const;
48
49   operator double () const { return to_double (); }
50   double to_double () const;
51
52   Rational operator - () const;
53   /**
54      Initialize to 0.
55   */
56   Rational ();
57   Rational (int);
58   explicit Rational (int, int);
59   explicit Rational (double);
60   Rational (Rational const &r) { copy (r);}
61   Rational &operator = (Rational const &r)
62   {
63     copy (r); return *this;
64   }
65
66   Rational &operator *= (Rational);
67   Rational &operator /= (Rational);
68   Rational &operator += (Rational);
69   Rational &operator -= (Rational);
70   Rational &operator %= (Rational);
71   static int compare (Rational const &, Rational const &);
72   int sign () const;
73   string to_string () const;
74 };
75
76 #include "arithmetic-operator.hh"
77
78 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, /);
79 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, +);
80 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, *);
81 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, -);
82 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, %);
83
84 INSTANTIATE_COMPARE (Rational const &, Rational::compare);
85
86 int compare (Rational const &, Rational const &);
87 int sign (Rational r);
88
89 inline void
90 Rational::copy (Rational const &r)
91 {
92   sign_ = r.sign_;
93   num_ = r.num_;
94   den_ = r.den_;
95 }
96
97 #if 0
98 ostream &
99 operator << (ostream &, Rational);
100 #endif
101
102 const Rational infinity_rat (INT_MAX);
103
104 #endif // RATIONAL_HH