Search code examples
c#.netmathconsolemathnet-numerics

How to display a derivative


Not sure this is the correct section of this site,but I have a question.

So,i`m using MathNet.Numerics to calculate a derivatives. I want to display them in console.

Code example

using System;
using MathNet.Numerics;

namespace math
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Func<double,double> f = x => 3 * Math.Pow(x, 3) + 2 * x - 6;
            var test = Differentiate.DerivativeFunc(f, 1);
            Console.WriteLine(test.ToString());
            Console.ReadKey();
        }
    }
}

Solution

  • Question

    Let me reword your problem to make sure I understand and answer you correctly: Given the function 3x³ + 2x - 6 you would like to print in the console the equation of the derivative 9x² + 2

    The library Math.NET Numerics can't do that

    This library does calculation. It does not try to construct the equation of the derivative.

    Look: Differentiate.DerivativeFunc method returns a C# method Func<double, double> that takes a double as parameter, and returns a double as the result. This signature makes it impossible to retrieve the equation of f'. Go deeper in the code and see that the library is all about computing results with an approximation.

    However Math.NET Symbolics can 😀

    https://symbolics.mathdotnet.com/ is what you are looking for. I wrote the following code:

    // using System;
    // using MathNet.Symbolics;
    // using Expr = MathNet.Symbolics.SymbolicExpression;
    
    var x = Expr.Variable("x");
    var func = 3 * (x * x * x) + 2 * x - 6;
    Console.WriteLine("f(x) = " + func.ToString());
    
    var derivative = func.Differentiate(x);
    Console.WriteLine("f'(x) = " + derivative.ToString());
    

    which prints in the console:

    f(x) = -6 + 2*x + 3*x^3

    f'(x) = 2 + 9*x^2