我看到我可以声明一个函数(比如说)
public double Function(double parameter)
Run Code Online (Sandbox Code Playgroud)
但是,如果我想采取该功能的衍生物怎么办?
pyo*_*yon 33
您无法使用计算机程序计算函数的精确导数(除非您正在进行符号数学......但这是另一种更复杂的主题).
有几种方法可以计算函数的数值导数.最简单的是居中的三点法:
[f(x+h) - f(x-h)] / 2h 另一种方法是中心五点法:
[f(x-2h) - 8f(x-h) + 8f(x+h) - f(x+2h)] / 12h另一个主题是如何使用C#实现它.首先,您需要一个代表一个函数的委托,该函数将实数的一个子集映射到另一个实数的子集:
delegate double RealFunction(double arg);
Run Code Online (Sandbox Code Playgroud)
然后,您需要一个评估衍生的路由:
public double h = 10e-6; // I'm not sure if this is valid C#, I'm used to C++
static double Derivative(RealFunction f, double arg)
{
double h2 = h*2;
return (f(x-h2) - 8*f(x-h) + 8*f(x+h) - f(x+h2)) / (h2*6);
}
Run Code Online (Sandbox Code Playgroud)
如果需要面向对象的实现,则应创建以下类:
interface IFunction
{
// Since operator () can't be overloaded, we'll use this trick.
double this[double arg] { get; }
}
class Function : IFunction
{
RealFunction func;
public Function(RealFunction func)
{ this.func = func; }
public double this[double arg]
{ get { return func(arg); } }
}
class Derivative : IFunction
{
IFunction func;
public static double h = 10e-6;
public Derivative(IFunction func)
{ this.func = func; }
public double this[double arg]
{
get
{
double h2 = h*2;
return (
func[arg - h2] - func[arg + h2] +
( func[arg + h] - func[arg - h] ) * 8
) / (h2 * 6);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您正在考虑对公式进行符号处理,那么您最好使用Maple或Mathematica等语言进行推导.它们是为符号计算而设计的.
编辑:如果Maple和Mathematica对你来说太昂贵,那么还有其他选择.维基百科有一个相当完整的计算机代数包列表.http://en.wikipedia.org/wiki/Comparison_of_computer_algebra_systems
您在考虑 Lambda 表达式吗?
基本上你可以将一个函数传递给另一个函数。
因此,请考虑对对象进行排序。根据对象的性质将有助于确定对象的排序方式。
但您仍然可以创建一个通用排序函数,然后传入如何比较对象。