]> 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--2004 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 */
8
9
10 #ifndef RATIONAL_HH
11 #define RATIONAL_HH
12
13 #include "string.hh"
14
15 /**
16    Rational numbers.  Included is support for + and - infinity.
17  */
18 class Rational {
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   //   operator bool () const;
46   int to_int () const;
47   operator double () const;
48   Rational operator - () const;
49   /**
50      Initialize to 0. 
51    */
52   Rational ();
53   Rational (int);
54   Rational (int, int);
55   Rational (double);
56   Rational (Rational const&r) {   copy (r);}
57   Rational &operator = (Rational const &r) {
58     copy (r); return *this;
59   }
60
61   Rational &operator *= (Rational);
62   Rational &operator /= (Rational);  
63   Rational &operator += (Rational);
64   Rational &operator -= (Rational);
65   Rational &operator %= (Rational);
66   static int compare (Rational const&, Rational const&);
67   int sign () const;
68   String to_string () const;
69 };
70
71 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, / );
72 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, + );
73 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, * );
74 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, - );
75 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, % );
76
77 INSTANTIATE_COMPARE (Rational const&, Rational::compare);
78
79 int compare (Rational const&,Rational const&);
80 int sign (Rational r);
81
82 inline void
83 Rational::copy (Rational const&r)
84 {
85   sign_ = r.sign_;
86   num_ = r.num_;
87   den_ = r.den_;
88 }
89
90 #if 0
91 ostream &
92 operator << (ostream &,  Rational);
93 #endif
94
95 const Rational infinity_rat = INT_MAX;
96
97 #endif // RATIONAL_HH