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 (int n, int d)
66 sign_ = ::sign (n) * ::sign (d);
72 Rational::Rational (int n)
81 Rational::set_infinite (int s)
83 sign_ = ::sign (s) * 2;
88 Rational::operator - () const
96 Rational::div_rat (Rational div) const
100 return r.trunc_rat ();
104 Rational::mod_rat (Rational div) const
107 r = (r / div - r.div_rat (div)) * div;
113 copy & paste from scm_gcd (GUILE).
127 /* Determine a common factor 2^k */
128 while (!(1 & (u | v)))
134 /* Now, any factor 2^n can be eliminated */
160 Rational::normalize ()
179 int g = gcd (num_, den_);
186 Rational::sign () const
188 return ::sign (sign_);
192 Rational::compare (Rational const &r, Rational const &s)
194 if (r.sign_ < s.sign_)
196 else if (r.sign_ > s.sign_)
198 else if (r.is_infinity ())
200 else if (r.sign_ == 0)
202 return r.sign_ * ::sign (int (r.num_ * s.den_) - int (s.num_ * r.den_));
206 compare (Rational const &r, Rational const &s)
208 return Rational::compare (r, s);
212 Rational::operator %= (Rational r)
219 Rational::operator += (Rational r)
223 else if (r.is_infinity ())
227 int lcm = (den_ / gcd (r.den_, den_)) * r.den_;
228 int n = sign_ * num_ * (lcm / den_) + r.sign_ * r.num_ * (lcm / r.den_);
230 sign_ = ::sign (n) * ::sign (d);
239 copied from libg++ 2.8.0
241 Rational::Rational (double x)
249 double mantissa = frexp (x, &expt);
251 const int FACT = 1 << 20;
254 Thanks to Afie for this too simple idea.
256 do not blindly substitute by libg++ code, since that uses
257 arbitrary-size integers. The rationals would overflow too
261 num_ = (unsigned int) (mantissa * FACT);
262 den_ = (unsigned int) FACT;
288 Rational::operator *= (Rational r)
290 sign_ *= ::sign (r.sign_);
291 if (r.is_infinity ())
306 Rational::operator /= (Rational r)
319 Rational::operator -= (Rational r)
326 Rational::to_string () const
330 string s (sign_ > 0 ? "" : "-");
331 return string (s + "infinity");
334 string s = ::to_string (num ());
335 if (den () != 1 && num ())
336 s += "/" + ::to_string (den ());
341 Rational::to_int () const
343 return (int) num () / den ();
353 Rational::is_infinity () const
355 return sign_ == 2 || sign_ == -2;