2 rational.cc -- implement Rational
4 source file of the Flower Library
6 (c) 1997 Han-Wen Nienhuys <hanwen@stack.nl>
11 #include "string-convert.hh"
12 #include "libc-extension.hh"
15 Rational::operator bool () const
21 operator << (ostream &o, Rational r)
30 Rational::truncated () const
32 return Rational(num_ - (num_ % den_), den_);
41 Rational::Rational (int n, int d)
43 sign_ = ::sign (n) * ::sign (d);
51 int gcd (int a, int b)
63 int lcm (int a, int b)
65 return abs (a*b / gcd (a,b));
69 Rational::set_infinite (int s)
71 sign_ = ::sign (s) * 2;
75 Rational::operator - () const
83 Rational::normalise ()
96 int g = gcd (num_ , den_);
103 Rational::sign () const
105 return ::sign (sign_);
109 Rational::infty_b () const
111 return abs (sign_) > 1;
115 Rational::compare (Rational const &r, Rational const &s)
117 if (r.sign_ < s.sign_)
119 else if (r.sign_ > s.sign_)
121 else if (r.infty_b ())
124 return (r - s).sign ();
128 compare (Rational const &r, Rational const &s)
130 return Rational::compare (r, s );
134 Rational::operator += (Rational r)
138 else if (r.infty_b ())
144 int n = sign_ * num_ *r.den_ + r.sign_ * den_ * r.num_;
145 int d = den_ * r.den_;
146 sign_ = ::sign (n) * ::sign(d);
156 copied from libg++ 2.8.0
158 Rational::Rational(double x)
167 const long shift = 15; // a safe shift per step
168 const double width = 32768.0; // = 2^shift
169 const int maxiter = 20; // ought not be necessary, but just in case,
170 // max 300 bits of precision
172 double mantissa = frexp(x, &expt);
173 long exponent = expt;
176 while (mantissa != 0.0 && k++ < maxiter)
179 mantissa = modf(mantissa, &intpart);
181 num_ += (long)intpart;
186 else if (exponent < 0)
204 Rational::operator *= (Rational r)
206 sign_ *= ::sign (r.sign_);
222 Rational::operator /= (Rational r)
235 Rational::operator -= (Rational r)
242 be paranoid about overiding libg++ stuff
245 Rational::operator = (Rational const &r)
251 Rational::Rational (Rational const &r)
256 Rational::operator String () const
262 Rational::str () const
266 String s (sign_ > 0 ? "" : "-" );
267 return String (s + "infinity");
270 if (den () != 1 && num ())
271 s += "/" + String (den ());