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_
;
21 operator << (ostream
&o
, Rational r
)
28 Rational::trunc_rat () const
30 return Rational (num_
- (num_
% den_
), den_
);
39 Rational::Rational (int n
, int d
)
41 sign_
= ::sign (n
) * ::sign (d
);
47 Rational::Rational (int n
)
55 int gcd (int a
, int b
)
67 int lcm (int a
, int b
)
69 return abs (a
*b
/ gcd (a
,b
));
73 Rational::set_infinite (int s
)
75 sign_
= ::sign (s
) * 2;
79 Rational::operator - () const
87 Rational::div_rat (Rational div
) const
91 return r
.trunc_rat ();
95 Rational::mod_rat (Rational div
) const
98 r
= (r
/ div
- r
.div_rat (div
)) * div
;
103 Rational::normalise ()
122 int g
= gcd (num_
, den_
);
129 Rational::sign () const
131 return ::sign (sign_
);
135 Rational::compare (Rational
const &r
, Rational
const &s
)
137 if (r
.sign_
< s
.sign_
)
139 else if (r
.sign_
> s
.sign_
)
141 else if (r
.infty_b ())
143 else if (r
.sign_
== 0)
147 return r
.sign_
* ::sign (int (r
.num_
* s
.den_
) - int (s
.num_
* r
.den_
));
152 compare (Rational
const &r
, Rational
const &s
)
154 return Rational::compare (r
, s
);
158 Rational::operator %= (Rational r
)
160 *this = r
.mod_rat (r
);
165 Rational::operator += (Rational r
)
169 else if (r
.infty_b ())
175 int n
= sign_
* num_
*r
.den_
+ r
.sign_
* den_
* r
.num_
;
176 int d
= den_
* r
.den_
;
177 sign_
= ::sign (n
) * ::sign (d
);
187 copied from libg++ 2.8.0
189 Rational::Rational (double x
)
197 double mantissa
= frexp (x
, &expt
);
199 const int FACT
= 1 << 20;
202 Thanks to Afie for this too simple idea.
204 do not blindly substitute by libg++ code, since that uses
205 arbitrary-size integers. The rationals would overflow too
209 num_
= (unsigned int) (mantissa
* FACT
);
210 den_
= (unsigned int) FACT
;
237 Rational::operator *= (Rational r
)
239 sign_
*= ::sign (r
.sign_
);
255 Rational::operator /= (Rational r
)
268 Rational::operator -= (Rational r
)
275 be paranoid about overiding libg++ stuff
278 Rational::operator = (Rational
const &r
)
285 Rational::str () const
289 String
s (sign_
> 0 ? "" : "-" );
290 return String (s
+ "infinity");
292 String s
= to_str (num ());
293 if (den () != 1 && num ())
294 s
+= "/" + to_str (den ());
299 Rational::to_int () const
301 return num () / den ();