数学函数微分与C#? [英] Mathematical function differentiation with C#?

查看:575
本文介绍了数学函数微分与C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以声明一个函数(说)

I see that I can declare a function with (say)

public double Function(double parameter)

但是如果我想采取这一函数的导数是什么?

but what if I do want to take the derivative of that function?

推荐答案

您无法计算使用计算机程序(除非你做符号数学函数的导数确切...但这是另一个,方式更加复杂,主题)。

You can't calculate the exact derivative of a function using a computer program (unless you're doing symbolic math... but that's another, way more complicated, topic).

有几种方法计算数值函数的导数。最简单的是为本三点法:

There are several approaches to computing a numerical derivative of a function. The simplest is the centered three-point method:


  • 取一数H

  • 评估 [F(X + H) - F(X-H)] /小时

  • 瞧,F'(X)的近似值,只有两个功能评价

另一种方法是在中心五点法:

Another approach is the centered five-point method:


  • 取一数H

  • 评估 [F(X-2H) - 8F(X-H)+ 8F(X + H) - F(X + 2H)/ 12小时

  • 瞧,F'(x)的更好的近似,但它需要更多的功能评价

另外一个话题是如何实现这一点使用C#。首先,你需要一个委托,它重新presents的实数的一个子集映射到一个实数的另一个子集的功能:

Another topic is how to implement this using C#. First, you need a delegate that represents a function that maps a subset of the real numbers onto a another subset of the real numbers:

delegate double RealFunction(double arg);

然后,你需要评估衍生物的路由:

Then, you need a routing that evaluates the derivative:

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

如果你想要一个面向对象的实现,你应该创建以下类:

If you want an object-oriented implementation, you should create the following classes:

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#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆