Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematica calls NMinimize with symbols rather than numbers?

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}}
like image 515
Sangeeta Bhatia Avatar asked Apr 27 '11 21:04

Sangeeta Bhatia


2 Answers

Have you tried defining your function to only evaluate for numeric input?

dummy[x_?NumericQ] := ...
like image 187
Mr.Wizard Avatar answered Sep 28 '22 06:09

Mr.Wizard


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] := ....
like image 37
Simon Avatar answered Sep 28 '22 05:09

Simon