I want to define a function that involves a differentiation step that Mathematica can do easily, which might be of the form
f[a_,b_,z_,j_]:=D[Hypergeometric1F1[a, b, z^2], {z, 2 j}]
(This will not work when given numeric z
, but that is only a small part of the problem.)
I will be using this for a limited set of j
's quite intensively in z
. It is therefore important to me that the symbolic differentiation only take place once, so that Mathematica is not repeatedly trying to do the same symbolic manipulations when running over a plot or a numerical integration.
What is the cleanest/most elegant way to do this sort of partial memoization procedure?
Answer
A general approach in this kind of situations is to use memoization. Here, however, some of the parameters should remain patterns (general), so you can use something like this (see this answer for a similar case):
ClearAll[f];
f[a_, b_, z_, j_] :=
Block[{al, bl, zl},
f[al_, bl_, zl_, j] = D[Hypergeometric1F1[al, bl, zl^2], {zl, 2 j}];
f[a, b, z, j]
]
Upon the first call, a special global rule (definition) will be created for any specific j
, and all subsequent calls with this j
will use this definition:
f[a,b,z,1]
(*
(2 a Hypergeometric1F1[1+a,1+b,z^2])/b+(4 a (1+a) z^2
Hypergeometric1F1[2+a,2+b,z^2])/(b (1+b))
*)
Inspecting the definition now:
?f
Global`f
f[al$_,bl$_,zl$_,1]=(2 al$ Hypergeometric1F1[1+al$,1+bl$,zl$^2])/bl$+
(4 al$ (1+al$) zl$^2 Hypergeometric1F1[2+al$,2+bl$,zl$^2])/(bl$ (1+bl$))
f[a_,b_,z_,j_]:=Block[{al,bl,zl},f[al_,bl_,zl_,j]=\!\(
\*SubscriptBox[\(\[PartialD]\), \({zl, 2\ j}\)]\(Hypergeometric1F1[al, bl,
\*SuperscriptBox[\(zl\), \(2\)]]\)\);f[a,b,z,j]]
Comments
Post a Comment