سؤال

I have the following function

public Func<double[], double> Function { get; set; }
this.Function = (x) => 
    Math.Exp(-Math.Pow(x[0] - 1, 2)) + Math.Exp(-0.5 * Math.Pow(x[1] - 2, 2));

and the gradient which is the partial derivatives of the function above

public Func<double[], double[]> Gradient { get; set; } 
this.Gradient = (x) => new double[] 
{
    // df/dx = -2 * e^(-(x - 1)²)(x - 1).
    -2 * Math.Exp(-Math.Pow(x[0] - 1, 2)) * (x[0] - 1),

    // df/dy = -e^(-1/2(y - 2)²) * (y - 2).
    -Math.Exp(-0.5 * Math.Pow(x[1] - 2, 2)) * (x[1] - 2)
};

To take the negation of the function I can do

Func<double[], double> oldFunc = this.Function;
this.Function = (x) => -oldFunc(x);

My question is, how can take the negation of each of the partial derivatives in gradient the same way?

هل كانت مفيدة؟

المحلول

using System.Linq;    

Func<double[], double[]> oldFunc = this.Gradient;
this.Gradient = (x) => oldFunc(x).Select( y => -y).ToArray();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top