4
$\begingroup$

I have a linear function which also follows the chain rule (it is a derivation), so I defined it recursively, following a Wolfram tutorial (which I've misplaced) and other related answers:

fn[f_+g_] := fn[f] + fn[g]
fn[f_ g_] := fn[f] g + f fn[g]

Unfortunately, I have to run this on polynomials with thousands of terms, which inevitably leads to

$RecursionLimit::reclim: Recursion depth of 1024 exceeded.

I get around the issue in certain specific cases by using Distribute, which doesn't work well with the recursive chain rule. For example:

(* fn[f_+g_]:= fn[f]+fn[g]; *)
fn[f_ g_] := fn[f] g + f fn[g];
Distribute[fn[x (y + z)]]

(* Out[1]= (y + z) fn[x] + x fn[y + z] *)

I have also previously raised the $RecursionLimit but I feel requiring my definition of fn to work with infinitely many recursions is probably a bad idea (since I eventually run into larger and larger polynomials, I inevitably keep raising the recursion limit until I get tired of doing so and remove the limit altogether).

My question is: are there any problems with using

fn[f__Plus] := Plus @@ (fn /@ (List@@f))

as an alternative to the recursive rule? My question is a bit leading, but I do feel suspicious of the answer that Apply is always preferable to the recursive definition.

$\endgroup$
1
  • $\begingroup$ If you are able to include code that generates an example polynomial that produces the recursion limit warning you may get better answers sooner, as it makes it less work to answer. $\endgroup$
    – Mr.Wizard
    Commented Mar 25, 2015 at 8:44

1 Answer 1

3
$\begingroup$

Lacking an example of your polynomial I did not attempt to test this extensively, but try:

ClearAll[fn]

fn[p_Plus] := fn /@ p

fn[f_ g_] := fn[f] g + f fn[g]
$\endgroup$
4
  • 1
    $\begingroup$ Here you are: x[] := Unique["x"]; poly = Times @@ Table[x[], {1024}] :) $\endgroup$
    – Kuba
    Commented Mar 25, 2015 at 8:52
  • $\begingroup$ @Kuba That's multiplication. I thought this question was about the additive rule? $\endgroup$
    – Mr.Wizard
    Commented Mar 25, 2015 at 9:00
  • $\begingroup$ Yes, probably you are right, OP didn't say how big those terms are really, you never know ;) $\endgroup$
    – Kuba
    Commented Mar 25, 2015 at 9:03
  • $\begingroup$ @Kuba's example is fine and I'm having trouble getting a MWE representing my specific problem so I'm starting to suspect I hit the recursion limit more from the chain rule (how you hit the recursion limit depends on how the expression is expanded, right?) than from the additive rule. Anyways, using /@ works better than what I wrote above and I think I'll mark this as a solution. Thanks! $\endgroup$
    – Eric
    Commented Mar 25, 2015 at 22:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.