我看到我可以用(比方说)声明一个函数
public double Function(double parameter)
但如果我确实想对该函数求导怎么办?
最佳答案
您无法使用计算机程序计算函数的精确导数(除非您在进行符号数学……但这是另一个更复杂的主题)。
有几种方法可以计算函数的数值导数。最简单的就是居中三点法:
- 取小数h
- 计算
[f(x+h) - f(x-h)]/2h
- Voilà,f'(x) 的近似值,只有两个函数求值
另一种方法是居中五点法:
- 取小数h
- 计算
[f(x-2h) - 8f(x-h) + 8f(x+h) - f(x+2h)]/12h
- 瞧,f'(x) 的更好近似值,但它需要更多的函数评估
另一个主题是如何使用 C# 实现它。首先,您需要一个代表函数的委托(delegate),该函数将实数的一个子集映射到实数的另一个子集:
delegate double RealFunction(double arg);
然后,您需要一个计算导数的路由:
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);
}
如果你想要一个面向对象的实现,你应该创建以下类:
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);
}
}
}
关于c# - 使用 C# 进行数学函数微分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/373186/