[英]How Can I Find Function's Value by MathNet in C#
我需要找到給定值的函數值。 例如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?
我應該使用評估方法嗎? 我怎樣才能做到這一點?
你的表達和評價不正確。
您可以執行一個將 x 作為參數的方法,並通過使用正確的代碼獲得正確的結果。
這是一個工作示例,其中包含對您的問題的內聯評論/解釋。 你可以改變你的等式,用它做任何事。 享受:
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;
}
現在運行它,並傳遞類似於f(1)
的MyFunc(1)
1) ,它返回-3
,傳遞MyFunc(2)
返回0
並傳遞MyFunc(3)
返回3
等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.