]> git.donarmstrong.com Git - lilypond.git/blob - flower/include/rational.hh
release: 1.5.10
[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
63   Rational &operator = (Rational const &);
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 str () const;
72 };
73
74 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, / );
75 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, + );
76 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, * );
77 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, - );
78 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, % );
79
80 INSTANTIATE_COMPARE (Rational const&, Rational::compare);
81
82 int compare (Rational const&,Rational const&);
83 int sign (Rational r);
84
85 inline void
86 Rational::copy (Rational const&r)
87 {
88   sign_ = r.sign_;
89   num_ = r.num_;
90   den_ = r.den_;
91 }
92
93 ostream &
94 operator << (ostream &,  Rational);
95
96 const Rational infinity_rat = INT_MAX;
97
98 #endif // RATIONAL_HH