Search code examples
wolfram-mathematica

Thread not applying properly to defined Module


I have a module that generates the nth Taylor polynomial for a function:

taylor[n_, a_] := 
 Module[{terms = {f[0]}}, 
  Do[AppendTo[
    terms, (D[f[x], {x, i}] /. x -> a)/Factorial[i]*(x - a)^i], {i, 1,
     n}]; Return[Plus @@ terms]]

Now, I want to call this function such that it generates a list of polynomials. This worked fine with a singular argument and Maping it over a Range. However, in trying to Thread the module like so:

Thread[taylor[Range[7], 0]]

I get an error that

Iterator {i,1,{1,2,3,4,5,6,7}} does not have appropriate bounds.

i.e., n is not being evaluated like I thought it would be, like:

{taylor[1,0], taylor[2,0], ...}

I could change the implementation of the module, but I do not know why Thread is not behaving as expected.


Solution

  • Try this and see if it does what you want

    taylor[n_, a_] := Module[{terms = {f[0]}}, 
      Do[AppendTo[terms, (D[f[x], {x, i}] /. x -> a)/Factorial[i]*(x - a)^i], {i, 1,n}]; 
      Return[Plus @@ terms]]
    Thread[g[{1,2,3},0]]/.g->taylor
    

    which returns

    {f[0] + x*f'[0],
     f[0] + x*f'[0] + x^2*f''[0]/2,
     f[0] + x*f'[0] + x^2*f''[0]/2 + x^3*f'''[0]/6}
    

    What that is doing is all the threading without invoking the way that Module evaluates arguments and once that is finished then handing it to Module to complete. Just make certain that you haven't defined g before you do this.

    Check all this very carefully before you depend on it.