2 rational.cc -- implement Rational
4 source file of the Flower Library
6 (c) 1997--2007 Han-Wen Nienhuys <hanwen@xs4all.nl>
16 #include "string-convert.hh"
17 #include "libc-extension.hh"
20 Rational::to_double () const
22 if (sign_
== -1 || sign_
== 1 || sign_
== 0)
23 return ((double)sign_
) * num_
/ den_
;
37 operator << (ostream
&o
, Rational r
)
45 Rational::abs () const
47 return Rational (num_
, den_
);
51 Rational::trunc_rat () const
53 return Rational (num_
- (num_
% den_
), den_
);
62 Rational::Rational (int n
, int d
)
64 sign_
= ::sign (n
) * ::sign (d
);
70 Rational::Rational (int n
)
79 Rational::set_infinite (int s
)
81 sign_
= ::sign (s
) * 2;
85 Rational::operator - () const
93 Rational::div_rat (Rational div
) const
97 return r
.trunc_rat ();
101 Rational::mod_rat (Rational div
) const
104 r
= (r
/ div
- r
.div_rat (div
)) * div
;
110 copy & paste from scm_gcd (GUILE).
124 /* Determine a common factor 2^k */
125 while (!(1 & (u
| v
)))
131 /* Now, any factor 2^n can be eliminated */
157 Rational::normalize ()
176 int g
= gcd (num_
, den_
);
183 Rational::sign () const
185 return ::sign (sign_
);
189 Rational::compare (Rational
const &r
, Rational
const &s
)
191 if (r
.sign_
< s
.sign_
)
193 else if (r
.sign_
> s
.sign_
)
195 else if (r
.is_infinity ())
197 else if (r
.sign_
== 0)
199 return r
.sign_
* ::sign (int (r
.num_
* s
.den_
) - int (s
.num_
* r
.den_
));
203 compare (Rational
const &r
, Rational
const &s
)
205 return Rational::compare (r
, s
);
209 Rational::operator %= (Rational r
)
216 Rational::operator += (Rational r
)
220 else if (r
.is_infinity ())
224 int lcm
= (den_
/ gcd (r
.den_
, den_
)) * r
.den_
;
225 int n
= sign_
* num_
* (lcm
/ den_
) + r
.sign_
* r
.num_
* (lcm
/ r
.den_
);
227 sign_
= ::sign (n
) * ::sign (d
);
236 copied from libg++ 2.8.0
238 Rational::Rational (double x
)
246 double mantissa
= frexp (x
, &expt
);
248 const int FACT
= 1 << 20;
251 Thanks to Afie for this too simple idea.
253 do not blindly substitute by libg++ code, since that uses
254 arbitrary-size integers. The rationals would overflow too
258 num_
= (unsigned int) (mantissa
* FACT
);
259 den_
= (unsigned int) FACT
;
285 Rational::operator *= (Rational r
)
287 sign_
*= ::sign (r
.sign_
);
288 if (r
.is_infinity ())
303 Rational::operator /= (Rational r
)
316 Rational::operator -= (Rational r
)
323 Rational::to_string () const
327 string
s (sign_
> 0 ? "" : "-");
328 return string (s
+ "infinity");
331 string s
= ::to_string (num ());
332 if (den () != 1 && num ())
333 s
+= "/" + ::to_string (den ());
338 Rational::to_int () const
340 return (int) num () / den ();
350 Rational::is_infinity () const
352 return sign_
== 2 || sign_
== -2;