]> git.donarmstrong.com Git - lilypond.git/blob - flower/include/rational.hh
2003 -> 2004
[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 "compare.hh"
14 #include "arithmetic-operator.hh"
15 #include "flower-proto.hh"
16 #include "string.hh"
17
18
19 /**
20    Rational numbers.  Included is support for + and - infinity.
21  */
22 class Rational {
23   /**
24      Sign of rational.
25      -2, .. 2
26
27      -2,2 is - and + infinity.
28      -1,1 is negative and positive.
29      0 if *this is zero.
30    */
31   int sign_;
32   unsigned int num_, den_;
33   void normalise ();
34   void copy (Rational const &);
35
36 public:
37   void set_infinite (int sign);
38   bool is_infinity () const;
39   void invert ();
40   int num () const { return sign_ * num_; }
41   int den () const { return den_; }
42
43   Rational trunc_rat () const;
44   Rational div_rat (Rational) const;
45   Rational mod_rat (Rational) const;
46   void negate ();
47   //   operator bool () const;
48   int to_int () const;
49   operator double () const;
50   Rational operator - () const;
51   /**
52      Initialize to 0. 
53    */
54   Rational ();
55   Rational (int);
56   Rational (int, int);
57   Rational (double);
58   Rational (Rational const&r) {   copy (r);}
59   Rational &operator = (Rational const &r) {
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