]> www.ginac.de Git - ginac.git/blobdiff - ginac/diff.cpp
- changed function::diff() to be more tolerant by checking first if the
[ginac.git] / ginac / diff.cpp
index ff7855af4f0854dd2e7868cfeb0e01454f890d16..2661fddb849bbab612c2aabf1a0bfec25d5c1333 100644 (file)
@@ -1,7 +1,8 @@
 /** @file diff.cpp
  *
- *  Implementation of symbolic differentiation in all of GiNaC's classes.
- *
+ *  Implementation of symbolic differentiation in all of GiNaC's classes. */
+
+/*
  *  GiNaC Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany
  *
  *  This program is free software; you can redistribute it and/or modify
@@ -36,6 +37,8 @@
 #include "series.h"
 #include "symbol.h"
 
+namespace GiNaC {
+
 /** Default implementation of ex::diff(). It prints and error message and returns a fail object.
  *  @see ex::diff */
 ex basic::diff(symbol const & s) const
@@ -172,17 +175,22 @@ ex power::diff(symbol const & s) const
 ex function::diff(symbol const & s) const
 {
     exvector new_seq;
-
-    if (serial == function_index_Order) {
-
+    
+    if (serial==function_index_Order) {
         // Order Term function only differentiates the argument
         return Order(seq[0].diff(s));
-
     } else {
-
         // Chain rule
+        ex arg_diff;
         for (unsigned i=0; i!=seq.size(); i++) {
-            new_seq.push_back(mul(pdiff(i), seq[i].diff(s)));
+            arg_diff = seq[i].diff(s);
+            // We apply the chain rule only when it makes sense.  This is not
+            // just for performance reasons but also to allow functions to
+            // throw when differentiated with respect to one of its arguments
+            // without running into trouble with our automatic full
+            // differentiation:
+            if (!arg_diff.is_zero())
+                new_seq.push_back(mul(pdiff(i), arg_diff));
         }
     }
     return add(new_seq);
@@ -197,7 +205,7 @@ ex series::diff(symbol const & s) const
         epvector new_seq;
         epvector::const_iterator it = seq.begin(), itend = seq.end();
         
-        //!! coeff might depend on var
+        // FIXME: coeff might depend on var
         while (it != itend) {
             if (is_order_function(it->rest)) {
                 new_seq.push_back(expair(it->rest, it->coeff - 1));
@@ -223,7 +231,7 @@ ex series::diff(symbol const & s) const
 
 ex ex::diff(symbol const & s, unsigned nth) const
 {
-    ASSERT(bp!=0);
+    GINAC_ASSERT(bp!=0);
 
     if ( nth==0 ) {
         return *this;
@@ -236,3 +244,5 @@ ex ex::diff(symbol const & s, unsigned nth) const
     }
     return ndiff;
 }
+
+} // namespace GiNaC