To implement what you intended to do, I suggest to take a look at this approach :
hermite[0, x_] := 1
hermite[1, x_] := 2 x
hermite[n_Integer /; n >= 2, x_] :=
hermite[n, x] = Expand[2 x*hermite[n - 1, x] - 2 (n - 1) hermite[n - 2, x]]
Now you shouldn't have problems anymore.
Recalling that there are in Mathematica
the Hermite polynomials $H_{n}(x)$ since the version 1, namely HermiteH
function, we can check if the above is correctly implemented :
And @@ SameQ @@@ ({hermite[#, x], HermiteH[#, x]} & /@ Range[100])
True
e.g.
hermite[10, x]
-30240 + 302400 x^2 - 403200 x^4 + 161280 x^6 - 23040 x^8 + 1024 x^10
The problem with your approach appears with so-called memoization of
2 x*hermite[n - 1, x] - 2 (n - 1) hermite[n - 2, x]
but not Expand[hermite[n, x]]
, so there you had i.e.
hermite[5, x]
2 x (12 - 48 x^2 + 16 x^4) - 8 (-8 x + 2 x (-2 + 4 x^2))
instead of
120 x - 160 x^3 + 32 x^5
We solved the problem by remembering
Expand[ 2 x*hermite[n - 1, x] - 2 (n - 1) hermite[n - 2, x] ]
To avoid another possible problems with the variable n
, I included a condition in the definition of hermite[n, x]
. In your approach you had i.e. hermite[1, x] = 2 x;
and so evaluating i.e.
Plot[{hermite[0, x], hermite[1, x]}, {x, -5, 5}] (* A *)
a message is generated $RecursionLimit::reclim
of exceeded $RecursionLimit
(by default its value is 256
). To avoid this problem you have do this :
Plot[ Evaluate @ {hermite[0, x], hermite[1, x]}, {x, -5, 5}] (* B *)
With my approach you needn't evaluate the functions, so you can choose (* A *).