]> git.donarmstrong.com Git - lilypond.git/blobdiff - flower/rational.cc
Fix #629.
[lilypond.git] / flower / rational.cc
index 150ace0359b6eedc234a9e41c8af7f6bed71a03b..4205b1d683042153a4fe41dfa6651bb343c75d70 100644 (file)
@@ -3,7 +3,7 @@
 
   source file of the Flower Library
 
-  (c) 1997--2006 Han-Wen Nienhuys <hanwen@xs4all.nl>
+  (c) 1997--2007 Han-Wen Nienhuys <hanwen@xs4all.nl>
 */
 
 #include "rational.hh"
@@ -16,7 +16,8 @@ using namespace std;
 #include "string-convert.hh"
 #include "libc-extension.hh"
 
-Rational::operator double () const
+double
+Rational::to_double () const
 {
   if (sign_ == -1 || sign_ == 1 || sign_ == 0)
     return ((double)sign_) * num_ / den_;
@@ -49,7 +50,9 @@ Rational::abs () const
 Rational
 Rational::trunc_rat () const
 {
-  return Rational (num_ - (num_ % den_), den_);
+  if (is_infinity())
+    return *this;
+  return Rational ((num_ - (num_ % den_)) * sign_, den_);
 }
 
 Rational::Rational ()
@@ -66,22 +69,19 @@ Rational::Rational (int n, int d)
   normalize ();
 }
 
-static inline
-int gcd (int a, int b)
+Rational::Rational (int n)
 {
-  int t;
-  while ((t = a % b))
-    {
-      a = b;
-      b = t;
-    }
-  return b;
+  sign_ = ::sign (n);
+  num_ = ::abs (n);
+  den_ = 1;
 }
 
+
 void
 Rational::set_infinite (int s)
 {
   sign_ = ::sign (s) * 2;
+  num_ = 1;
 }
 
 Rational
@@ -108,6 +108,54 @@ Rational::mod_rat (Rational div) const
   return r;
 }
 
+
+/*
+  copy & paste from scm_gcd (GUILE).
+ */
+static int
+gcd (long u, long v) 
+{
+  long result = 0;
+  if (u == 0)
+    result = v;
+  else if (v == 0)
+    result = u;
+  else
+    {
+      long k = 1;
+      long t;
+      /* Determine a common factor 2^k */
+      while (!(1 & (u | v)))
+       {
+         k <<= 1;
+         u >>= 1;
+         v >>= 1;
+       }
+      /* Now, any factor 2^n can be eliminated */
+      if (u & 1)
+       t = -v;
+      else
+       {
+         t = u;
+       b3:
+         t = t >> 1;
+       }
+      if (!(1 & t))
+       goto b3;
+      if (t > 0)
+       u = t;
+      else
+       v = -t;
+      t = u - v;
+      if (t != 0)
+       goto b3;
+      result = u * k;
+    }
+
+  return result;
+}
+
+
 void
 Rational::normalize ()
 {