I noticed the following behavior while using NMinimize
in Mathematica. The first invocation of the objective function is with variable names, rather than with points from the space, as one would expect.
So for example if my objective function is a module, this module is called only once, evaluated symbolically and then in further iterations, this symbolic expression is evaluated with points from the variable space.
This behavior could slow down the computation significantly for a large expression.
Is there any way to get around this? Has anyone else experienced this? Is there any way to speed up NMinimize
then?
Example:
dummy[x_] := Module[
{},
Print["x=", x ];
4 x^4 - 4 x^2 + 1
]
In: NMinimize[dummy[x], x]
Out:x=x
{0., {x -> 0.707107}}
Have you tried defining your function to only evaluate for numeric input?
dummy[x_?NumericQ] := ...
For some dummy functions an "exact numeric" call can also be very slow. Example finding the FixedPoint[Sqrt,2.]
is fast, but FixedPoint[Sqrt,2]
will go until something breaks!
By "exact numeric" I mean things like Integers
, Rationals
, and numeric symbolics like Sqrt[2]
, Cos[5]
, Pi
, EulerGamma
, etc...
that is, things that will return a numerical value when acted upon by N[]
.
In this case it is probably better to use
dummy[_?InexactNumberQ] := ....
or even
dummy[_?MachineNumberQ] := ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With