public static T FindMin(IFunctional <T> functional, IParametricFunction <T> function, IVector <T> s, IVector <T> p, T eps) { var la = LinearAlgebra.Value; var a = la.Cast(0); var b = la.Cast(1e2); var x = la.Sum(a, la.Mult(la.Mult(la.Cast(0.5), la.Sub(la.Cast(3), la.Sqrt(la.Cast(5.0)))), (la.Sub(b, a)))); var y = la.Sum(la.Sub(b, x), a); var fx = function.Bind(s.AddWithCloning(p.MultWithCloning(la.Mult(x, la.Cast(-1))))); var fy = function.Bind(s.AddWithCloning(p.MultWithCloning(la.Mult(y, la.Cast(-1))))); var valueX = functional.Value(fx); var valueY = functional.Value(fy); while (la.Compare(la.Abs(la.Sub(b, a)), la.Cast(1e-5)) == 1) { if (la.Compare(valueX, valueY) == -1) { b = y; y = x; fy = fx; valueY = valueX; x = la.Sub(la.Sum(b, a), y); fx = function.Bind(s.AddWithCloning(p.MultWithCloning(la.Mult(x, la.Cast(-1))))); valueX = functional.Value(fx); } else { a = x; x = y; fx = fy; valueX = valueY; y = la.Sub(la.Sum(b, a), x); fy = function.Bind(s.AddWithCloning(p.MultWithCloning(la.Mult(y, la.Cast(-1))))); valueY = functional.Value(fy); } } return(la.Div(la.Sum(a, b), la.Cast(2))); }
public IVector <T> Minimize(IFunctional <T> objective, IParametricFunction <T> function, IVector <T> initialParameters, IVector <T> minimumParameters = default, IVector <T> maximumParameters = default) { var k = 0; var la = LinearAlgebra.Value; IVector <T> xPrev = initialParameters.Clone() as IVector <T>; IVector <T> xNew = initialParameters.Clone() as IVector <T>; var normalDist = new Normal(Mean, StdDev); T prevValue = objective.Value(function.Bind(xPrev)); do { var t = 20d / Math.Log(k, Math.E); for (int i = 0; i < xPrev.Count; i++) { var nR = normalDist.Sample() * t; xNew[i] = la.Sum(xPrev[i], la.Cast(nR)); } this.ApplyMinimumAndMaximumValues(minimumParameters, maximumParameters, xNew, la); var newValue = objective.Value(function.Bind(xNew)); var sub = la.Sub(newValue, prevValue); if (la.Compare(sub, la.GetZeroValue()) == -1) // || la.Exp(la.Mult(la.Cast(-1/t), sub)) >= rand.NextDouble()) { prevValue = newValue; xPrev = xNew.Clone() as IVector <T>; } } while ((MaxIter.HasValue && MaxIter > k++ && la.Compare(prevValue, Eps) == 1) || (!MaxIter.HasValue && la.Compare(prevValue, Eps) == 1)); return(xPrev); }