2 rational.cc -- implement Rational
4 source file of the Flower Library
6 (c) 1997--2000 Han-Wen Nienhuys <hanwen@cs.uu.nl>
10 #include "rational.hh"
12 #include "string-convert.hh"
13 #include "libc-extension.hh"
15 Rational::operator bool () const
20 Rational::operator int () const
22 return sign_
* num_
/ den_
;
25 Rational::operator double () const
27 return (double)sign_
* num_
/ den_
;
31 operator << (ostream
&o
, Rational r
)
38 Rational::trunc_rat () const
40 return Rational(num_
- (num_
% den_
), den_
);
49 Rational::Rational (int n
, int d
)
51 sign_
= ::sign (n
) * ::sign (d
);
58 int gcd (int a
, int b
)
70 int lcm (int a
, int b
)
72 return abs (a
*b
/ gcd (a
,b
));
76 Rational::set_infinite (int s
)
78 sign_
= ::sign (s
) * 2;
82 Rational::operator - () const
90 Rational::div_rat (Rational div
) const
94 return r
.trunc_rat ();
98 Rational::mod_rat (Rational div
) const
101 r
= (r
/ div
- r
.div_rat (div
)) * div
;
106 Rational::normalise ()
119 int g
= gcd (num_
, den_
);
126 Rational::sign () const
128 return ::sign (sign_
);
132 Rational::infty_b () const
134 return abs (sign_
) > 1;
138 Rational::compare (Rational
const &r
, Rational
const &s
)
140 if (r
.sign_
< s
.sign_
)
142 else if (r
.sign_
> s
.sign_
)
144 else if (r
.infty_b ())
147 return (r
- s
).sign ();
151 compare (Rational
const &r
, Rational
const &s
)
153 return Rational::compare (r
, s
);
157 Rational::operator %= (Rational r
)
159 *this = r
.mod_rat (r
);
164 Rational::operator += (Rational r
)
168 else if (r
.infty_b ())
174 int n
= sign_
* num_
*r
.den_
+ r
.sign_
* den_
* r
.num_
;
175 int d
= den_
* r
.den_
;
176 sign_
= ::sign (n
) * ::sign(d
);
186 copied from libg++ 2.8.0
188 Rational::Rational(double x
)
196 double mantissa
= frexp(x
, &expt
);
198 const int FACT
= 1 << 20;
201 Thanks to Afie for this too simple idea.
203 do not blindly substitute by libg++ code, since that uses
204 arbitrary-size integers. The rationals would overflow too
208 num_
= (unsigned int) (mantissa
* FACT
);
209 den_
= (unsigned int) FACT
;
236 Rational::operator *= (Rational r
)
238 sign_
*= ::sign (r
.sign_
);
254 Rational::operator /= (Rational r
)
267 Rational::operator -= (Rational r
)
274 be paranoid about overiding libg++ stuff
277 Rational::operator = (Rational
const &r
)
284 Rational::str () const
288 String
s (sign_
> 0 ? "" : "-" );
289 return String (s
+ "infinity");
291 String s
= to_str (num ());
292 if (den () != 1 && num ())
293 s
+= "/" + to_str (den ());