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 double () const
17 return (double)sign_
* num_
/ den_
;
22 operator << (ostream
&o
, Rational r
)
31 Rational::trunc_rat () const
33 return Rational (num_
- (num_
% den_
), den_
);
42 Rational::Rational (int n
, int d
)
44 sign_
= ::sign (n
) * ::sign (d
);
50 Rational::Rational (int n
)
58 int gcd (int a
, int b
)
71 int lcm (int a
, int b
)
73 return abs (a
*b
/ gcd (a
,b
));
78 Rational::set_infinite (int s
)
80 sign_
= ::sign (s
) * 2;
84 Rational::operator - () const
92 Rational::div_rat (Rational div
) const
96 return r
.trunc_rat ();
100 Rational::mod_rat (Rational div
) const
103 r
= (r
/ div
- r
.div_rat (div
)) * div
;
108 Rational::normalise ()
127 int g
= gcd (num_
, den_
);
134 Rational::sign () const
136 return ::sign (sign_
);
140 Rational::compare (Rational
const &r
, Rational
const &s
)
142 if (r
.sign_
< s
.sign_
)
144 else if (r
.sign_
> s
.sign_
)
146 else if (r
.infty_b ())
148 else if (r
.sign_
== 0)
152 return r
.sign_
* ::sign (int (r
.num_
* s
.den_
) - int (s
.num_
* r
.den_
));
157 compare (Rational
const &r
, Rational
const &s
)
159 return Rational::compare (r
, s
);
163 Rational::operator %= (Rational r
)
165 *this = r
.mod_rat (r
);
170 Rational::operator += (Rational r
)
174 else if (r
.infty_b ())
180 int n
= sign_
* num_
*r
.den_
+ r
.sign_
* den_
* r
.num_
;
181 int d
= den_
* r
.den_
;
182 sign_
= ::sign (n
) * ::sign (d
);
192 copied from libg++ 2.8.0
194 Rational::Rational (double x
)
202 double mantissa
= frexp (x
, &expt
);
204 const int FACT
= 1 << 20;
207 Thanks to Afie for this too simple idea.
209 do not blindly substitute by libg++ code, since that uses
210 arbitrary-size integers. The rationals would overflow too
214 num_
= (unsigned int) (mantissa
* FACT
);
215 den_
= (unsigned int) FACT
;
242 Rational::operator *= (Rational r
)
244 sign_
*= ::sign (r
.sign_
);
260 Rational::operator /= (Rational r
)
273 Rational::operator -= (Rational r
)
280 Rational::to_string () const
284 String
s (sign_
> 0 ? "" : "-" );
285 return String (s
+ "infinity");
288 String s
= ::to_string (num ());
289 if (den () != 1 && num ())
290 s
+= "/" + ::to_string (den ());
295 Rational::to_int () const
297 return num () / den ();