]> git.donarmstrong.com Git - lilypond.git/blob - flower/include/rational.hh
Use long long integers in Rational class.
[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--2007 Han-Wen Nienhuys <hanwen@xs4all.nl>
7 */
8
9 #ifndef RATIONAL_HH
10 #define RATIONAL_HH
11
12 #include "flower-proto.hh"
13 #include "std-string.hh"
14 #include <limits.h>
15
16 /**
17    Rational numbers.  Included is support for + and - infinity.
18 */
19 class Rational
20 {
21   /**
22      Sign of rational.
23      -2, .. 2
24
25      -2,2 is - and + infinity.
26      -1,1 is negative and positive.
27      0 if *this is zero.
28   */
29   int sign_;
30   U64 num_, den_;
31   void normalize ();
32   void copy (Rational const &);
33
34 public:
35   void set_infinite (int sign);
36   bool is_infinity () const;
37   void invert ();
38   I64 numerator () const { return sign_ * num_; }
39   I64 denominator () const { return den_; }
40   I64 num () const { return numerator (); }
41   I64 den () const { return denominator (); }
42
43   Rational trunc_rat () const;
44   Rational div_rat (Rational) const;
45   Rational mod_rat (Rational) const;
46   Rational abs () const;
47   void negate ();
48   int to_int () const;
49
50   operator double () const { return to_double (); }
51   double to_double () const;
52
53   Rational operator - () const;
54   /**
55      Initialize to 0.
56   */
57   Rational ();
58   Rational (int);
59   Rational (I64);
60   explicit Rational (I64, I64);
61   explicit Rational (double);
62   Rational (Rational const &r) { copy (r);}
63   Rational &operator = (Rational const &r)
64   {
65     copy (r); return *this;
66   }
67
68   Rational &operator *= (Rational);
69   Rational &operator /= (Rational);
70   Rational &operator += (Rational);
71   Rational &operator -= (Rational);
72   Rational &operator %= (Rational);
73   static int compare (Rational const &, Rational const &);
74   int sign () const;
75   string to_string () const;
76 };
77
78 #include "arithmetic-operator.hh"
79
80 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, /);
81 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, +);
82 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, *);
83 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, -);
84 IMPLEMENT_ARITHMETIC_OPERATOR (Rational, %);
85
86 INSTANTIATE_COMPARE (Rational const &, Rational::compare);
87
88 int compare (Rational const &, Rational const &);
89 int sign (Rational r);
90
91 inline void
92 Rational::copy (Rational const &r)
93 {
94   sign_ = r.sign_;
95   num_ = r.num_;
96   den_ = r.den_;
97 }
98
99 #if 0
100 ostream &
101 operator << (ostream &, Rational);
102 #endif
103
104 const Rational infinity_rat (LLONG_MAX);
105
106 #endif // RATIONAL_HH