0

I can plot my function penalty[v] just fine, but FindMinimum doesn't work, it just complains non-numerical values from NIntegrate.

gau[x_, v_] := Exp[-(x^2)/(2*v)]/Sqrt[2*Pi*v];
data = {-5, -4, -3, 1, 2};
p[x_, v_] := Total[gau[x - data, v]]/Length[data];
penalty[v_] := Sum[Log[p[data[[i]], v]], {i, 1, Length[data]}]/Length[data]-NIntegrate[p[x, v]*Log[p[x, v]], {x, -Infinity, Infinity}];
Plot[penalty[v], {v, .01, 2}]
FindMinimum[penalty[v], {v, .25}]

What am I doing wrong?

(Side note: In my definition of penalty, I had to use Sum instead of Mean because when data is passed into p[x_,v_], the data-data yields zeros instead of the cross terms. Should I have coded that part differently too?)

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Jerry Guern
  • 4,602
  • 18
  • 47
  • Prevent symbolic evaluation using NumericQ i.e. define penalty[v_?NumericQ] := restOfCode. That should then work: result. See: http://mathematica.stackexchange.com/a/26037/27951 – MarcoB Jun 09 '16 at 20:49
  • @MarcoB Thank you, that works. But nothing I've find in the docs helps me understand WHY that works. As I understand the ?NumericQ suffix, it should just penalty[] not work if the v input wasn't numeric. Is FindMinimum[] figuring out somehow that it needs to provide numeric inputs? If you put a little bit of explanation into an Answer, I can Accept it. Thanks again. – Jerry Guern Jun 09 '16 at 20:58
  • Have you had a chance to take a look at the FAQ I linked to? That should give you a head start. – MarcoB Jun 09 '16 at 21:00

0 Answers0