Search code examples
c#evaluatemathnet-numerics

How Can I Find Function's Value by MathNet in C#


I need to find the function's value for the given value. For example, the function is 3x-6, and I would like to find f(1),

using MathNet.Numerics;
using MathNet.Symbolics;
using Expr = MathNet.Symbolics.SymbolicExpression;        
        
var x = Expr.Variable("x");
var func = 3*x - 6;
// var value = func.Evaluate?

Should I use method of evaluate? How can I do this?


Solution

  • Your expression and evaluation is not correct.

    You can do a method that takes x as parameter and by using the right code you get the right result.

    Here is an working example with inline comments/explanation to your question. You can change your equation and do what ever with it. Enjoy:

    public static double MyFunc(int x)
    {
        // pass one or multiple variable in equation
        var variables = new Dictionary<string, FloatingPoint>
        {
            { "x", x }
        };
    
        //transfer equation from string to expression
        Expression expression = Infix.ParseOrThrow("3*x-6");
        
        //evaluate the result in double
        double result = Evaluate.Evaluate(variables, expression).RealValue;
        return result;
    }
    

    Now run it, and pass MyFunc(1) which is like f(1), it returns -3, pass MyFunc(2) returns 0 and pass MyFunc(3) returns 3 and so on etc.