]> git.donarmstrong.com Git - lilypond.git/blob - flower/include/rational.hh
nitpick: fix double include.
[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--2006 Han-Wen Nienhuys <hanwen@xs4all.nl>
7 */
8
9 #ifndef RATIONAL_HH
10 #define RATIONAL_HH
11
12 #include "std-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 normalize ();
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   Rational abs () const;
45   void negate ();
46   int to_int () const;
47
48   operator double () const;
49
50   Rational operator - () const;
51   /**
52      Initialize to 0.
53   */
54   Rational ();
55   Rational (int);
56   explicit Rational (int, int);
57   explicit Rational (double);
58   Rational (Rational const &r) { copy (r);}
59   Rational &operator = (Rational const &r)
60   {
61     copy (r); return *this;
62   }
63
64   Rational &operator *= (Rational);
65   Rational &operator /= (Rational);
66   Rational &operator += (Rational);
67   Rational &operator -= (Rational);
68   Rational &operator %= (Rational);
69   static int compare (Rational const &, Rational const &);
70   int sign () const;
71   string to_string () const;
72 };
73
74 #include "arithmetic-operator.hh"
75
76 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, /);
77 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, +);
78 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, *);
79 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, -);
80 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, %);
81
82 INSTANTIATE_COMPARE (Rational const &, Rational::compare);
83
84 int compare (Rational const &, Rational const &);
85 int sign (Rational r);
86
87 inline void
88 Rational::copy (Rational const &r)
89 {
90   sign_ = r.sign_;
91   num_ = r.num_;
92   den_ = r.den_;
93 }
94
95 #if 0
96 ostream &
97 operator << (ostream &, Rational);
98 #endif
99
100 const Rational infinity_rat (INT_MAX);
101
102 #endif // RATIONAL_HH