简体   繁体   English

如何通过 MathNet 在 C# 中找到函数的值

[英]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),例如function是3x-6,求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?我怎样才能做到这一点?

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.您可以执行一个将 x 作为参数的方法,并通过使用正确的代码获得正确的结果。

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.现在运行它,并传递类似于f(1)MyFunc(1) 1) ,它返回-3 ,传递MyFunc(2)返回0并传递MyFunc(3)返回3等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM