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