I was trying to evaluate a sum over a piecewise function, not unlike this example. However, my piecewise function needed to be defined differently for even and odd k
. This is a simpler version of my function, just so we can all agree that the sum exists:
f[k_]:=Piecewise[{{1, k==0}, {x^k/k!, OddQ[k]}, {x^k/k!, EvenQ[k]}}]
(I keep x
and k
undefined throughout. I know that this could be simplified, but this is just for the purposes of having a minimal working example.)
If, for example, I evaluate f[3]
, I get x^3/6
, as expected. Or if I do
Sum[f[k], {k,0,5}]
I get the expected answer -- a nice little sum of terms involving powers of x
. I can also do
Sum[x^k/k!, {k, 0, Infinity}]
And get E^x
, as expected.
But if I evaluate
Sum[f[k], {k, 0, Infinity}]
I get 1
. And, when I evaluate f[k]
, I get
Piecewise[{{1, k == 0}}, 0]
And yet, it still knows that f[k]
is not just this when I pass an actual integer (e.g., 3
), or ask for a finite Sum
; it actually does remember more about f
than these results suggest.
What is going on?
Edit
As J.M. pointed out in the comments, apparently OddQ
and EvenQ
evaluate on a symbol, before it is known whether it represents an integer -- never mind an even or odd one. The solution (adding IntegerPart
) to the question george2079 linked does not help. But J.M. did suggest a workaround: change OddQ[k]
to Mod[k,2]==1
, and EvenQ[k]
to Mod[k,2]==0
. (I maintain that mathematica should be a little more clever about when it evaluates things, rather than silently given the right answer to a question I didn't mean to ask. But I guess it's legacy code by now.)
EvenQ[]
andOddQ[]
returnFalse
for any input that is manifestly not an integer. Use checks based onMod[]
instead. $\endgroup$OddQ[expr]
returnsTrue
only ifexpr
is an odd integer. $\endgroup$Positive[x]
does NOT return False, because it understands that x might be positive, so it returnsPositive[x]
, unless we tell it something more aboutx
. The same symbolic behaviour would be desirable for the ___Q funcs, such asEvenQ
,OddQ
etc ... which currently are basically numeric functions, and which, in my view, operate in a manner that appears inconsistent with the symbolic underpinnings of Mma. $\endgroup$*Q[]
functions are not intended to remain inert; they must return eitherTrue
orFalse
. Granted, a version ofOddQ[]
/EvenQ[]
that remains inert for ambiguous arguments would be useful… $\endgroup$