]> git.donarmstrong.com Git - lilypond.git/blob - flower/include/rational.hh
release: 1.5.17
[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--2000 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 infty_b () const
39     {
40       return sign_ == 2 || sign_ == -2;
41     }
42   void invert ();
43   int num () const { return sign_ * num_; }
44   int den () const { return den_; }
45
46   Rational trunc_rat () const;
47   Rational div_rat (Rational) const;
48   Rational mod_rat (Rational) const;
49   void negate ();
50   //   operator bool () const;
51   int to_int () const;
52   operator double () const;
53   Rational operator - () const;
54   /**
55      Initialize to 0. 
56    */
57   Rational ();
58   Rational (int);
59   Rational (int, int);
60   Rational (double);
61   Rational (Rational const&r) {   copy (r);}
62   Rational &operator = (Rational const &r) {
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 str () const;
74 };
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 ostream &
96 operator << (ostream &,  Rational);
97
98 const Rational infinity_rat = INT_MAX;
99
100 #endif // RATIONAL_HH