1
$\begingroup$

I have an extremely simple question, but I couldn't find anything anywhere, maybe I didn't know what to search for, so feel free to mark it as duplicate if there is a duplicate.

Let's say that I define some function, for example

f[p_Integer] := Sum[k!/(k^2 - 3), {k, 0, p}].

If I want to evaluate it for some integer, for example f[10], it works, as expected. But what if I want to evaluate it for a variable, for example f[n], how do I tell Mathematica to do it? I get f[n] as the result, but that's not so useful.

I'm interested in the general solution, nevermind my example, I had to use something.

$\endgroup$
3
$\begingroup$

Well, you told M that the argument to f must have Integer head. So when you said f[n] and n is not integer, then M did not know what to do and returned back the input. If you wanted f to be evaluated for non integer heads, you can do

ClearAll[n,f,p]
f[p_Integer]:=Sum[k!/(k^2-3),{k,0,p}]
f[p_]:=Sum[k!/(k^2-3),{k,0,p}]  (*or can also use f[p_Symbol]*)

Now

f[5]

Mathematica graphics

f[n]

Mathematica graphics

| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ It is useful to note that f[5] == (f[n] /. n -> 5) evaluates to True, i.e., the DifferenceRoot gives the same result as the integer input. Consequently, while the definition for integer input is efficient, it is computationally redundant. $\endgroup$ – Bob Hanlon Nov 27 '17 at 0:25
  • $\begingroup$ Great, thank you, I really needed the f[p_Integer] specification, so I didn't know how to do both, this works! $\endgroup$ – PhysSE is Cancer Nov 27 '17 at 1:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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