I am writing a Monte Carlo algorithm to solve some algebraic equations. To do this I need to evaluate FindRoot many times on the same function. Following from F'x's answer to Expression evaluation inside of FindRoot inside a Compiled Function, I understand that FindRoot will compile the target function each time it is evaluated, and so the fastest way for me to work with FindRoot is to combine the function myself beforehand. This should save FindRoot compiling each time I run it.
I can't however work out the syntax to do this. My toy example code is:
f[x_] := x^x + (4 - x)^(4 - x) - 10
g = Compile[{x}, x^x + (4 - x)^(4 - x) - 10];
FindRoot[f[x], {x, 3.99}, Compiled -> False] // Timing
FindRoot[f[x], {x, 3.99}] // Timing
FindRoot[g[x], {x, 3.99}, Compiled -> False] // Timing
FindRoot[g[x], {x, 3.99}] // Timing
None of the ones with g
work; I get CompiledFunction::cfsa
, and the g
ones are slower so I assume this is inputting the uncompiled function.
I have tried also
FindRoot[g, {x, 3.99}]
FindRoot[g, {x, 3.99},Compiled-> False]
Which don't evaluate to anything.
What is the correct syntax for this? Or if I've misunderstood the quoted article, could someone explain what I should be doing?
FindRoot[g, {3.99}]
. If a function is supplied, no symbol is needed. If you would like to use Newton's method, you have to supply a (compiled) functionDg
also for theJacobian
, e.g. withFindRoot[g, {3.99}, Jacobian -> Dg]
. For scalar function one may have to fiddle a bit with braces inDg
such thatDg[x]
becomes a 1 x 1 matrix; Mathematica will complain otherwise. $\endgroup$FindRoot
many times on the same function? Won't it always return the same answer? I assume the function must have some changes upon each invocation ofFindRoot
. Could you clarify what these changes are? $\endgroup$FindRoot
and just gave it a try. $\endgroup$