I'm a noob when it comes to DownValues
, UpValues
, OwnValues
, etc. but I figured I would give it a shot in my code because I think it would be beneficial for my work.
What I'm wondering is is it possible to set a DownValue
for a compiled function? I've searched the docs and haven't come up with anything about DownValue's for compiled functions. Consider the following example
ClearAll[f, cf]
f[x_] := (x^2 + x)/x
cf[0.] = 1.;
cf = Compile[{x}, Evaluate[f[x]], CompilationTarget -> "C"];
cf[0.]
(*output*)
Indeterminate
The uncompiled function simplifies to an expression that has a clearly defined value at x=0, but the compiled function doesn't know that, so I'm trying to set a downvalue for the compiled function at the apparent singularity to rid this effect. This is only a simple example, the function that's relevant to me is much more complicated unfortunately, but has the same apparent singularity at the origin. If I could set a downvalue for the compiled function, that would be tremendously helpful.
Maybe something with OwnValues
would work better here?
edit:
Ah, My ignorance on the types of values is showing. I see setting cf[0.]=1
sets the DownValue
for the symbol cf, while setting cf = Compile...
sets the OwnValue
for cf. So, one possible solution to this would be
ClearAll[f, cf]
f[x_] := (x^2 + x)/x
compiledf = Compile[{x}, Evaluate[f[x]], CompilationTarget -> "C"];
cf[0.] = 1.;
cf[a_] := compiledf[a];
cf[0.]
(*output*)
1.
But this is a bit of an ad hoc solution. Also the definition of compiledf needs to follow the definition of cf since:
DownValues[cf]
(*output*)
(*{HoldPattern[cf[0.]] :> 1., HoldPattern[cf[a_]] :> compiledf[a]}*)
So compiledf
would also need to be passed to a subkernel if cf
is ever passed to one, which is a bit inconvenient.
Maybe someone else has a better solution?