取消Func <double [],double [] =“”> </double [],>

时间:2014-02-10 13:24:52

标签: c# func

我有以下功能

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));

和梯度,它是上述函数的偏导数

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

取消我可以做的function

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

我的问题是,如何以同样的方式否定gradient中的每个偏导数?

1 个答案:

答案 0 :(得分:2)

using System.Linq;    

Func<double[], double[]> oldFunc = this.Gradient;
this.Gradient = (x) => oldFunc(x).Select( y => -y).ToArray();