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
55 return Rational ((num_ - (num_ % den_)) * sign_, den_);
64 Rational::Rational (I64 n, I64 d)
66 sign_ = ::sign (n) * ::sign (d);
72 Rational::Rational (I64 n)
79 Rational::Rational (U64 n)
86 Rational::Rational (int n)
95 Rational::set_infinite (int s)
97 sign_ = ::sign (s) * 2;
102 Rational::operator - () const
110 Rational::div_rat (Rational div) const
114 return r.trunc_rat ();
118 Rational::mod_rat (Rational div) const
121 r = (r / div - r.div_rat (div)) * div;
127 copy & paste from scm_gcd (GUILE).
141 /* Determine a common factor 2^k */
142 while (!(1 & (u | v)))
148 /* Now, any factor 2^n can be eliminated */
174 Rational::normalize ()
193 I64 g = gcd (num_, den_);
200 Rational::sign () const
202 return ::sign (sign_);
206 Rational::compare (Rational const &r, Rational const &s)
208 if (r.sign_ < s.sign_)
210 else if (r.sign_ > s.sign_)
212 else if (r.is_infinity ())
214 else if (r.sign_ == 0)
216 return r.sign_ * ::sign ((I64) (r.num_ * s.den_) - (I64) (s.num_ * r.den_));
220 compare (Rational const &r, Rational const &s)
222 return Rational::compare (r, s);
226 Rational::operator %= (Rational r)
233 Rational::operator += (Rational r)
237 else if (r.is_infinity ())
241 I64 lcm = (den_ / gcd (r.den_, den_)) * r.den_;
242 I64 n = sign_ * num_ * (lcm / den_) + r.sign_ * r.num_ * (lcm / r.den_);
244 sign_ = ::sign (n) * ::sign (d);
253 copied from libg++ 2.8.0
255 Rational::Rational (double x)
263 double mantissa = frexp (x, &expt);
265 const int FACT = 1 << 20;
268 Thanks to Afie for this too simple idea.
270 do not blindly substitute by libg++ code, since that uses
271 arbitrary-size integers. The rationals would overflow too
275 num_ = (U64) (mantissa * FACT);
302 Rational::operator *= (Rational r)
304 sign_ *= ::sign (r.sign_);
305 if (r.is_infinity ())
320 Rational::operator /= (Rational r)
333 Rational::operator -= (Rational r)
340 Rational::to_string () const
344 string s (sign_ > 0 ? "" : "-");
345 return string (s + "infinity");
348 string s = ::to_string (num ());
349 if (den () != 1 && num ())
350 s += "/" + ::to_string (den ());
355 Rational::to_int () const
357 return (int) num () / den ();
367 Rational::is_infinity () const
369 return sign_ == 2 || sign_ == -2;