因此,我拥有用于MATLAB中非线性方程求解的最速下降算法。我正在尝试使其在C#中工作。我已经重写了大部分内容,但是现在我被困在那部分,我应该在那儿获得2函数/方程系统的目标。
MATLAB中的目标函数:
% Target function
function rez=target(x)
rez=f(x)'*f(x)/2;
return
end
f(x)
在这里定义:
function fff=f(x)
fff=[x(1)^2+x(2)^2-2;
x(1)^2-x(2)^2];
return
end
到目前为止,我在C#中拥有的代码(我具有函数的输入和带有偏导数的渐变函数):
// System of 2 nonlinear functions
Vector<double> Func(double x1, double x2)
{
// First function of the system
double f = Math.Pow(Math.Sin(x1 / 2), 3) + Math.Pow(Math.Cos(x2 / 2), 2) - 0.5;
// Second function of the system
double s = Math.Pow(x2 - 3, 2) + Math.Pow(x1, 2) + x1 * x2 - 4;
return Vector<double>.Build.DenseOfArray(new double[] { f, s });
}
// Gradient of a 2 nonlinear functions system
Vector<double> Gradient(double x1, double x2)
{
// Partial derivative of function1 by x1
double f1 = 1.5 * Math.Pow(Math.Sin(x1 / 2), 2) * Math.Cos(x1 / 2);
// Partial derivative of function1 by x2
double f2 = -0.5 * Math.Sin(x2);
// Partial derivative of function2 by x1
double s1 = 2 * x1 + x2;
// Partial derivative of function2 by x2
double s2 = 2 * x2 - 6 + x1;
return Vector<double>.Build.DenseOfArray(new double[] { f1, f2, s1, s2 });
}
MATLAB中最速下降的整个算法(您可以看到在何处使用target(x)
函数):
eps=1e-5;
step0=0.5;
step=step0;
itmax=10 % amount of how many times the direction of movement can be changed
x=[-3;4]; % start
for iii=1:itmax
grad=gradient(x);
target1=target(x);
for j=1:30 % moving that direction, where the function is decreasing
deltax=grad/norm(grad)*step;
x=x-deltax';
target2=target(x);
if target2 > target1, x=x+deltax';
step=step/10;
else, target1=target2;
end
end
step=step0;
precision=norm(target1);
fprintf(1,'\n direction %d precision %g',iii,precision);
if precision < eps, fprintf(1,'\n solution x =');
fprintf(1,' %g',x);
break;
elseif iii == itmax,fprintf(1,'\n ****precision could not be reached. Last
point x =');
fprintf(1,' %g',x); break;
end
end
return
end
因此要在C#中实现最速下降算法来求解非线性方程,我要做的就是以某种方式在我的C#程序中定义MATLAB中的target(x)
函数,但我不知道该怎么做,也许有人可以帮助我?