Mathematica calls NMinimize with symbols rather than numbers?

落花浮王杯 提交于 2019-12-22 05:06:41

问题


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}}

回答1:


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

dummy[x_?NumericQ] := ...



回答2:


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] := ....


来源:https://stackoverflow.com/questions/5810588/mathematica-calls-nminimize-with-symbols-rather-than-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!