]> www.ginac.de Git - ginac.git/blobdiff - ginac/numeric.cpp
- The status_flags::expanded is now used on some occasions.
[ginac.git] / ginac / numeric.cpp
index f0db1ad9a126877d114d980841aa0761e12c0112..94012384f6377aea088ae4253bbb61ad99260aa5 100644 (file)
@@ -94,9 +94,10 @@ numeric::numeric() : basic(TINFO_numeric)
 {
     debugmsg("numeric default constructor", LOGLEVEL_CONSTRUCT);
     value = new cl_N;
-    *value=cl_I(0);
+    *value = cl_I(0);
     calchash();
-    setflag(status_flags::evaluated|
+    setflag(status_flags::evaluated |
+            status_flags::expanded |
             status_flags::hash_calculated);
 }
 
@@ -146,7 +147,7 @@ numeric::numeric(int i) : basic(TINFO_numeric)
 {
     debugmsg("numeric constructor from int",LOGLEVEL_CONSTRUCT);
     // Not the whole int-range is available if we don't cast to long
-    // first. This is due to the behaviour of the cl_I-ctor, which
+    // first.  This is due to the behaviour of the cl_I-ctor, which
     // emphasizes efficiency:
     value = new cl_I((long) i);
     calchash();
@@ -159,7 +160,7 @@ numeric::numeric(unsigned int i) : basic(TINFO_numeric)
 {
     debugmsg("numeric constructor from uint",LOGLEVEL_CONSTRUCT);
     // Not the whole uint-range is available if we don't cast to ulong
-    // first. This is due to the behaviour of the cl_I-ctor, which
+    // first.  This is due to the behaviour of the cl_I-ctor, which
     // emphasizes efficiency:
     value = new cl_I((unsigned long)i);
     calchash();
@@ -261,13 +262,13 @@ numeric::numeric(const archive_node &n, const lst &sym_lst) : inherited(n, sym_l
             case 'N':    // Ordinary number
             case 'R':    // Integer-decoded real number
                 s >> re.sign >> re.mantissa >> re.exponent;
-                *value = re.sign * re.mantissa * expt(cl_float(2.0, cl_default_float_format), re.exponent);
+                *value = re.sign * re.mantissa * ::expt(cl_float(2.0, cl_default_float_format), re.exponent);
                 break;
             case 'C':    // Integer-decoded complex number
                 s >> re.sign >> re.mantissa >> re.exponent;
                 s >> im.sign >> im.mantissa >> im.exponent;
-                *value = complex(re.sign * re.mantissa * expt(cl_float(2.0, cl_default_float_format), re.exponent),
-                                 im.sign * im.mantissa * expt(cl_float(2.0, cl_default_float_format), im.exponent));
+                *value = ::complex(re.sign * re.mantissa * ::expt(cl_float(2.0, cl_default_float_format), re.exponent),
+                                 im.sign * im.mantissa * ::expt(cl_float(2.0, cl_default_float_format), im.exponent));
                 break;
             default:   // Ordinary number
                                s.putback(c);
@@ -286,13 +287,13 @@ numeric::numeric(const archive_node &n, const lst &sym_lst) : inherited(n, sym_l
         switch (c) {
             case 'R':    // Integer-decoded real number
                 f >> re.sign >> re.mantissa >> re.exponent;
-                *value = re.sign * re.mantissa * expt(cl_float(2.0, cl_default_float_format), re.exponent);
+                *value = re.sign * re.mantissa * ::expt(cl_float(2.0, cl_default_float_format), re.exponent);
                 break;
             case 'C':    // Integer-decoded complex number
                 f >> re.sign >> re.mantissa >> re.exponent;
                 f >> im.sign >> im.mantissa >> im.exponent;
-                *value = complex(re.sign * re.mantissa * expt(cl_float(2.0, cl_default_float_format), re.exponent),
-                                 im.sign * im.mantissa * expt(cl_float(2.0, cl_default_float_format), im.exponent));
+                *value = ::complex(re.sign * re.mantissa * ::expt(cl_float(2.0, cl_default_float_format), re.exponent),
+                                 im.sign * im.mantissa * ::expt(cl_float(2.0, cl_default_float_format), im.exponent));
                 break;
             default:   // Ordinary number
                                f.putback(c);
@@ -511,11 +512,11 @@ bool numeric::info(unsigned inf) const
     case info_flags::negative:
         return is_negative();
     case info_flags::nonnegative:
-        return compare(_num0())>=0;
+        return !is_negative();
     case info_flags::posint:
         return is_pos_integer();
     case info_flags::negint:
-        return is_integer() && (compare(_num0())<0);
+        return is_integer() && is_negative();
     case info_flags::nonnegint:
         return is_nonneg_integer();
     case info_flags::even:
@@ -529,13 +530,17 @@ bool numeric::info(unsigned inf) const
 }
 
 /** Disassemble real part and imaginary part to scan for the occurrence of a
- *  single number.  Also handles the imaginary unit. */
+ *  single number.  Also handles the imaginary unit.  It ignores the sign on
+ *  both this and the argument, which may lead to what might appear as funny
+ *  results:  (2+I).has(-2) -> true.  But this is consistent, since we also
+ *  would like to have (-2+I).has(2) -> true and we want to think about the
+ *  sign as a multiplicative factor. */
 bool numeric::has(const ex & other) const
 {
     if (!is_exactly_of_type(*other.bp, numeric))
         return false;
     const numeric & o = static_cast<numeric &>(const_cast<basic &>(*other.bp));
-    if (this->is_equal(o))
+    if (this->is_equal(o) || this->is_equal(-o))
         return true;
     if (o.imag().is_zero())  // e.g. scan for 3 in -3*I
         return (this->real().is_equal(o) || this->imag().is_equal(o) ||
@@ -551,7 +556,7 @@ bool numeric::has(const ex & other) const
 }
 
 
-/** Evaluation of numbers doesn't do anything. */
+/** Evaluation of numbers doesn't do anything at all. */
 ex numeric::eval(int level) const
 {
     // Warning: if this is ever gonna do something, the ex ctors from all kinds
@@ -604,6 +609,16 @@ bool numeric::is_equal_same_type(const basic & other) const
     return this->is_equal(*o);
 }
 
+unsigned numeric::calchash(void) const
+{
+    return (hashvalue=cl_equal_hashcode(*value) | 0x80000000U);
+    /*
+    cout << *value << "->" << hashvalue << endl;
+    hashvalue=HASHVALUE_NUMERIC+1000U;
+    return HASHVALUE_NUMERIC+1000U;
+    */
+}
+
 /*
 unsigned numeric::calchash(void) const
 {
@@ -936,7 +951,7 @@ bool numeric::is_crational(void) const
 bool numeric::operator<(const numeric & other) const
 {
     if (this->is_real() && other.is_real())
-        return (bool)(The(cl_R)(*value) < The(cl_R)(*other.value));  // -> CLN
+        return (The(cl_R)(*value) < The(cl_R)(*other.value));  // -> CLN
     throw (std::invalid_argument("numeric::operator<(): complex inequality"));
     return false;  // make compiler shut up
 }
@@ -947,7 +962,7 @@ bool numeric::operator<(const numeric & other) const
 bool numeric::operator<=(const numeric & other) const
 {
     if (this->is_real() && other.is_real())
-        return (bool)(The(cl_R)(*value) <= The(cl_R)(*other.value));  // -> CLN
+        return (The(cl_R)(*value) <= The(cl_R)(*other.value));  // -> CLN
     throw (std::invalid_argument("numeric::operator<=(): complex inequality"));
     return false;  // make compiler shut up
 }
@@ -958,7 +973,7 @@ bool numeric::operator<=(const numeric & other) const
 bool numeric::operator>(const numeric & other) const
 {
     if (this->is_real() && other.is_real())
-        return (bool)(The(cl_R)(*value) > The(cl_R)(*other.value));  // -> CLN
+        return (The(cl_R)(*value) > The(cl_R)(*other.value));  // -> CLN
     throw (std::invalid_argument("numeric::operator>(): complex inequality"));
     return false;  // make compiler shut up
 }
@@ -969,7 +984,7 @@ bool numeric::operator>(const numeric & other) const
 bool numeric::operator>=(const numeric & other) const
 {
     if (this->is_real() && other.is_real())
-        return (bool)(The(cl_R)(*value) >= The(cl_R)(*other.value));  // -> CLN
+        return (The(cl_R)(*value) >= The(cl_R)(*other.value));  // -> CLN
     throw (std::invalid_argument("numeric::operator>=(): complex inequality"));
     return false;  // make compiler shut up
 }
@@ -1044,12 +1059,12 @@ numeric numeric::numer(void) const
         if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_I_ring))
             return numeric(*this);
         if (::instanceof(r, cl_I_ring) && ::instanceof(i, cl_RA_ring))
-            return numeric(complex(r*::denominator(The(cl_RA)(i)), ::numerator(The(cl_RA)(i))));
+            return numeric(::complex(r*::denominator(The(cl_RA)(i)), ::numerator(The(cl_RA)(i))));
         if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_I_ring))
-            return numeric(complex(::numerator(The(cl_RA)(r)), i*::denominator(The(cl_RA)(r))));
+            return numeric(::complex(::numerator(The(cl_RA)(r)), i*::denominator(The(cl_RA)(r))));
         if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_RA_ring)) {
-            cl_I s = lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i)));
-            return numeric(complex(::numerator(The(cl_RA)(r))*(exquo(s,::denominator(The(cl_RA)(r)))),
+            cl_I s = ::lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i)));
+            return numeric(::complex(::numerator(The(cl_RA)(r))*(exquo(s,::denominator(The(cl_RA)(r)))),
                                    ::numerator(The(cl_RA)(i))*(exquo(s,::denominator(The(cl_RA)(i))))));
         }
     }
@@ -1063,12 +1078,12 @@ numeric numeric::numer(void) const
         if (instanceof(r, cl_I_ring) && instanceof(i, cl_I_ring))
             return numeric(*this);
         if (instanceof(r, cl_I_ring) && instanceof(i, cl_RA_ring))
-            return numeric(complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
+            return numeric(::complex(r*TheRatio(i)->denominator, TheRatio(i)->numerator));
         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
-            return numeric(complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
+            return numeric(::complex(TheRatio(r)->numerator, i*TheRatio(r)->denominator));
         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring)) {
-            cl_I s = lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
-            return numeric(complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
+            cl_I s = ::lcm(TheRatio(r)->denominator, TheRatio(i)->denominator);
+            return numeric(::complex(TheRatio(r)->numerator*(exquo(s,TheRatio(r)->denominator)),
                                    TheRatio(i)->numerator*(exquo(s,TheRatio(i)->denominator))));
         }
     }
@@ -1099,7 +1114,7 @@ numeric numeric::denom(void) const
         if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_I_ring))
             return numeric(::denominator(The(cl_RA)(r)));
         if (::instanceof(r, cl_RA_ring) && ::instanceof(i, cl_RA_ring))
-            return numeric(lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i))));
+            return numeric(::lcm(::denominator(The(cl_RA)(r)), ::denominator(The(cl_RA)(i))));
     }
 #else
     if (instanceof(*value, cl_RA_ring)) {
@@ -1115,7 +1130,7 @@ numeric numeric::denom(void) const
         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_I_ring))
             return numeric(TheRatio(r)->denominator);
         if (instanceof(r, cl_RA_ring) && instanceof(i, cl_RA_ring))
-            return numeric(lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
+            return numeric(::lcm(TheRatio(r)->denominator, TheRatio(i)->denominator));
     }
 #endif // def SANE_LINKER
     // at least one float encountered
@@ -1153,7 +1168,7 @@ const numeric some_numeric;
 const type_info & typeid_numeric=typeid(some_numeric);
 /** Imaginary unit.  This is not a constant but a numeric since we are
  *  natively handing complex numbers anyways. */
-const numeric I = numeric(complex(cl_I(0),cl_I(1)));
+const numeric I = numeric(::complex(cl_I(0),cl_I(1)));
 
 
 /** Exponential function.
@@ -1429,9 +1444,11 @@ const numeric bernoulli(const numeric & nn)
         return _num0();
     // Until somebody has the Blues and comes up with a much better idea and
     // codes it (preferably in CLN) we make this a remembering function which
-    // computes its results using the formula
+    // computes its results using the defining formula
     // B(nn) == - 1/(nn+1) * sum_{k=0}^{nn-1}(binomial(nn+1,k)*B(k))
     // whith B(0) == 1.
+    // Be warned, though: the Bernoulli numbers are probably computationally 
+    // very expensive anyhow and you shouldn't expect miracles to happen.
     static vector<numeric> results;
     static int highest_result = -1;
     int n = nn.sub(_num2()).div(_num2()).to_int();
@@ -1463,23 +1480,50 @@ const numeric bernoulli(const numeric & nn)
  *  @exception range_error (argument must be an integer) */
 const numeric fibonacci(const numeric & n)
 {
-    if (!n.is_integer()) {
+    if (!n.is_integer())
         throw (std::range_error("numeric::fibonacci(): argument must be integer"));
-    }
-    // For positive arguments compute the nearest integer to
-    // ((1+sqrt(5))/2)^n/sqrt(5).  For negative arguments, apply an additional
-    // sign.  Note that we are falling back to longs, but this should suffice
-    // for all times.
-    int sig = 1;
-    const long nn = ::abs(n.to_double());
-    if (n.is_negative() && n.is_even())
-        sig =-1;
+    // The following addition formula holds:
+    //      F(n+m)   = F(m-1)*F(n) + F(m)*F(n+1)  for m >= 1, n >= 0.
+    // (Proof: For fixed m, the LHS and the RHS satisfy the same recurrence
+    // w.r.t. n, and the initial values (n=0, n=1) agree. Hence all values
+    // agree.)
+    // Replace m by m+1:
+    //      F(n+m+1) = F(m)*F(n) + F(m+1)*F(n+1)      for m >= 0, n >= 0
+    // Now put in m = n, to get
+    //      F(2n) = (F(n+1)-F(n))*F(n) + F(n)*F(n+1) = F(n)*(2*F(n+1) - F(n))
+    //      F(2n+1) = F(n)^2 + F(n+1)^2
+    // hence
+    //      F(2n+2) = F(n+1)*(2*F(n) + F(n+1))
+    if (n.is_zero())
+        return _num0();
+    if (n.is_negative())
+        if (n.is_even())
+            return -fibonacci(-n);
+        else
+            return fibonacci(-n);
     
-    // Need a precision of ((1+sqrt(5))/2)^-n.
-    cl_float_format_t prec = ::cl_float_format((int)(0.208987641*nn+5));
-    cl_R sqrt5 = ::sqrt(::cl_float(5,prec));
-    cl_R phi = (1+sqrt5)/2;
-    return numeric(::round1(::expt(phi,nn)/sqrt5)*sig);
+    cl_I u(0);
+    cl_I v(1);
+    cl_I m = The(cl_I)(*n.value) >> 1L;  // floor(n/2);
+    for (uintL bit=::integer_length(m); bit>0; --bit) {
+        // Since a squaring is cheaper than a multiplication, better use
+        // three squarings instead of one multiplication and two squarings.
+        cl_I u2 = ::square(u);
+        cl_I v2 = ::square(v);
+        if (::logbitp(bit-1, m)) {
+            v = ::square(u + v) - u2;
+            u = u2 + v2;
+        } else {
+            u = v2 - ::square(v - u);
+            v = u2 + v2;
+        }
+    }
+    if (n.is_even())
+        // Here we don't use the squaring formula because one multiplication
+        // is cheaper than two squarings.
+        return u * ((v << 1) - u);
+    else
+        return ::square(u) + ::square(v);    
 }