public void MultiValuedParametersTest() { var expr = new Expression("Pow((a * b), c)", EvaluateOptions.IgnoreCase | EvaluateOptions.IterateParameters); expr.Parameters["a"] = new[] { 1, 2, 3, 4, 5 }; expr.Parameters["b"] = new[] { 6, 7, 8, 9, 0 }; expr.Parameters["c"] = 3; foreach(var result in (IList)expr.Evaluate()) { Console.WriteLine(result); } }
public static IEnumerable<double> UnaryEvaluate(this string expression, string parameterName, Func<double[]> parameterFunc) { expression.ShouldNotBeWhiteSpace("expression"); var expr = new NCalc.Expression(expression, EvaluateOptions.IgnoreCase | EvaluateOptions.IterateParameters); expr.Parameters["x"] = parameterFunc(); return ((IList)expr.Evaluate()).Cast<object>().Select(result => result.AsDouble()); }
private void EQUALS() { if (InProgress == true) { try { SecondNumber = Convert.ToDouble(Display.Text); } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { try { FirstNumber = Convert.ToDouble(Display.Text); InProgress = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } } // calculates both numbers using the set operator, Using NClac Library NCalc.Expression ee = new NCalc.Expression(FirstNumber + Operation + SecondNumber); Result = Convert.ToDouble(ee.Evaluate()); Display.Text = Convert.ToString(Result); LastResult.Content = "Current Result: " + FirstNumber + Operation + SecondNumber + " = " + Result; SecondNumber = Result; }
protected void Page_Load(object sender, EventArgs e) { string equation = getRandomEquation(5); lblRandomEquation.Text = equation; NCalc.Expression ex = new NCalc.Expression(equation); lblResult.Text = (ex.Evaluate().ToString()); }
public RuleEngineRule(string id, string name, string expression) { Id = id; Name = name; RuleExpression = expression; Expression = new Expression(expression); }
/// <summary> /// /// </summary> /// <param name="element"></param> /// <param name="evp"></param> public override void Visit(Syntax.Expression element, EvaluationParam evp) { var a = new NCalc.Expression(element.formula).Evaluate(); result = new Result(); result.Value = a; }
private void btnCalculate_Click(object sender, EventArgs e) { #if !DEBUG try { #endif string format = txtFormat.Text; IEnumerable<string> expressions = GetExpressions(format); foreach (string expression in expressions) { Expression expr = new Expression(MakeParseable(expression)) { Parameters = GetParameters() }; string result = expr.Evaluate().ToString(); format = format.Replace(expression, result); } txtCalculated.Text = format; #if !DEBUG } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } #endif }
public static EDataTable CalculateTimeSliceTable() { foreach (var simpleFormulaModel in _timeSliceFormulas) { _timeSliceTable.Columns.Add(simpleFormulaModel.Name, typeof(double)); foreach (DataRow row in _timeSliceTable.Rows) { _expression = new Expression(simpleFormulaModel.Formula); foreach (var column in simpleFormulaModel.UsedColumns) { double rowValue; if (double.TryParse(row[column].ToString(), out rowValue)) _expression.Parameters[column] = rowValue; } try { var result = _expression.Evaluate(); row[simpleFormulaModel.Name] = result; } catch (Exception) { row[simpleFormulaModel.Name] = -1; } } } return _timeSliceTable; }
public void ClickEqualButton(object sender, EventArgs e) { isChengeOp = false; int amount = 0; for (int i = 0; i < eText.Length; i++) { if (eText[i] == '(') { amount++; } else if (eText[i] == ')') { amount--; } } for (int i = 0; i < amount; i++) { eText += ")"; Field.Text += ")"; } Calculate(); try { expression = new NCalc.Expression(eText); expression.Parameters["p"] = 3.14; expression.Parameters["e"] = 2.71828; Field.Text = expression.Evaluate().ToString().Replace(",", "."); eText = expression.Evaluate().ToString().Replace(",", "."); } catch { } }
public void HandleMessage(string command, string args, object clientData, Action<string, AnswerBehaviourType> sendMessageFunc) { Expression expr = new Expression(args); var exprAnswer = expr.Evaluate(); string messageAuthor = string.Empty; string answer = string.Empty; var skypeData = clientData as ISkypeData; if (skypeData!=null) { messageAuthor = skypeData.FromName; } if (!string.IsNullOrEmpty(messageAuthor)) { answer = string.Format("Мсье {0}, ответ равен : {1}", messageAuthor, exprAnswer); } else { answer = string.Format("Ответ равен : {0}", exprAnswer); } sendMessageFunc(answer, AnswerBehaviourType.Text); }
/// <summary> /// Setts up the Arcade. /// </summary> /// <param name='screen'> /// Screen. /// </param> public static void Loading(int arcadeOrArendelle) { Console.Title = " "; Console.Clear (); if (arcadeOrArendelle == 0) { string loadingText = "A R C A D E I D E " + InterfaceView.ArcadeVersion () + " "; string show = ""; for (int i = 0; i < loadingText.Length; i++) { Console.Clear (); show = show + loadingText[i].ToString(); InterfaceView.CenterWriter (-1, show); System.Threading.Thread.Sleep (50); } } else { InterfaceView.CenterWriter (-1, "L O A D I N G "); } // running a very easy problem with NCalc // so the runtime loads NCalc ( if we don't // do the very first Spaces.calculate will // take seconds! Expression vari = new Expression ("2*3+1"); vari.Evaluate (); if (arcadeOrArendelle == 0) System.Threading.Thread.Sleep (1000); }
/// <summary> /// 公式轉數值 /// </summary> /// <param name="rules">公式</param> /// <param name="array">陣列</param> /// <returns>數值</returns> public static double RulesToDouble(String rules, ref double[] array) { if (String.IsNullOrEmpty(rules)) return 0.0d; String rule = rules .Replace("@3", array[3].ToString()) .Replace("@4", array[4].ToString()) .Replace("@5", array[5].ToString()) .Replace("@6", array[6].ToString()) .Replace("@7", array[7].ToString()) .Replace("@8", array[8].ToString()) .Replace("@9", array[9].ToString()) .Replace("@10", array[10].ToString()) .Replace("@11", array[11].ToString()) .Replace("@12", array[12].ToString()) .Replace("@2", array[2].ToString()) .Replace("@1", array[1].ToString()) .Replace("@0", array[0].ToString()); try { Expression number = new Expression(rule); return Double.Parse(number.Evaluate().ToString()); } catch { } return 0.0d; }
public void Evaluate(Expression exp, Expression derExp, double a, double b, double tolerance) { addToLog("Starting Newton Method"); double expX, derExpX, result; double current = a; double previous = 0; while (true) { iteration++; // Functions expX = evaluate(exp, current); derExpX = evaluate(derExp, current); result = current - (expX / derExpX); // log addToLog(newLine + "Iteration: " + iteration); addToLog("F(x)= " + RoundDigit(expX, 4) + tab + "F'(x)= " + RoundDigit(derExpX, 4) + tab + "x= " + RoundDigit(result, 4)); // swaps previous = current; current = result; bool withinTolerance = inTolerance(tolerance, previous, current); if (withinTolerance) break; } addToLog("ROOT FOUND: " + result); }
public override Value Evaluate(FSharpList<Value> args) { var e = new Expression(Formula); var functionLookup = new Dictionary<string, Value>(); foreach (var arg in args.Select((arg, i) => new { Value = arg, Index = i })) { var parameter = InPortData[arg.Index].NickName; if (arg.Value.IsFunction) functionLookup[parameter] = arg.Value; else e.Parameters[parameter] = ((Value.Number)arg.Value).Item; } e.EvaluateFunction += delegate(string name, FunctionArgs fArgs) { if (functionLookup.ContainsKey(name)) { var func = ((Value.Function)functionLookup[name]).Item; fArgs.Result = ((Value.Number)func.Invoke( Utils.SequenceToFSharpList( fArgs.Parameters.Select<Expression, Value>( p => Value.NewNumber(Convert.ToDouble(p.Evaluate())))))).Item; } else { fArgs.HasResult = false; } }; return Value.NewNumber(Convert.ToDouble(e.Evaluate())); }
private double CalculateResult(string overallExpression) { NCalc.Expression expr = new NCalc.Expression(overallExpression); Func <double> f = expr.ToLambda <double>(); return(f()); }
private void buttonTest_Click(object sender, EventArgs e) { float textValue; float start; float end; try { textValue = float.Parse(textBoxTestInput.Text); start = float.Parse(textBoxRangeStart.Text); end = float.Parse(textBoxRangeEnd.Text); } catch (Exception) { MessageBox.Show("不正确的输入", "Error"); return; } if (textValue < start || textValue > end) { labelTestResult.Text = "not in range, did not cal"; return; } String realExp = textBoxExp.Text.Replace("t", textBoxTestInput.Text); try { Expression ex = new Expression(realExp); labelTestResult.Text = ex.Evaluate().ToString(); } catch(Exception excep) { MessageBox.Show(excep.ToString(), "Error"); } }
private void textBox_TextChanged(object sender, TextChangedEventArgs e) { var textBox = sender as TextBox; if (textBox != null) { if (textBox.Text != "") { expression = new Expression(textBox.Text); var paras = GetParametersInExpression(textBox.Text).Distinct().ToList(); if (paras.Any()) { RemoveAllInputPortsFromNode(paras); var filteredParas = paras.Where(parameter => InputPorts.All(p => p.Name != parameter)).ToList(); foreach (var parameter in filteredParas) AddInputPortToNode(parameter, typeof (object)); } } else { expression = null; RemoveAllInputPortsFromNode(); } } Calculate(); }
public void PlusMinusTest() { var expr = new Expression("2 + 3 * 5"); expr.Evaluate().Should().Be(17); expr = new Expression("48/(2*(9+3))"); expr.Evaluate().Should().Be(2d); }
public void ClickEqualButton(object sender, EventArgs e) { int amount = 0; for (int i = 0; i < Field.Text.Length; i++) { if (Field.Text[i] == '(') { amount++; } else if (Field.Text[i] == ')') { amount--; } } for (int i = 0; i < amount; i++) { Field.Text += ")"; } Calculate(); try { expression = new NCalc.Expression(Answer.Text); expression.Parameters["π"] = 3.14; expression.Parameters["e"] = 2.718281828459045; Field.Text = expression.Evaluate().ToString(); } finally { } }
private void Calculate() { try { string tmp = Field.Text; int amount = 0; for (int i = 0; i < tmp.Length; i++) { if (tmp[i] == '(') { amount++; } else if (tmp[i] == ')') { amount--; } } for (int i = 0; i < amount; i++) { tmp += ")"; } expression = new NCalc.Expression(tmp); expression.Parameters["π"] = 3.14; //expression.Parameters["e"] = 2.71828; Answer.Text = expression.Evaluate().ToString(); } catch { Answer.Text = ""; } }
public static bool Eval(object parameterValue, string strExpression) { Expression expression = new Expression(strExpression); expression.Parameters["p"] = parameterValue; bool flag = true; return flag.Equals(expression.Evaluate()); }
public bool ParseInt(out int value) { bool parsed = false; value = 0; if (IsValid) { try { NCalc.Expression expr = new NCalc.Expression(Expression); LogicalExpression pexpr = NCalc.Expression.Compile(Expression, false); ExprVisitor v = new ExprVisitor(); pexpr.Accept(v); if (!v.ComplexExpression) { value = Convert.ToInt32(expr.Evaluate()); parsed = true; } } catch (Exception) { } } return(parsed); }
/// <summary> /// Creates a new instance of the FunctionConverterClass /// </summary> /// <param name="function">The function as a string</param> /// <param name="length"></param> /// <param name="interval"></param> /// <param name="type">The type of data the function represents</param> public FunctionConverter(String function, double length, double interval, int type) { int size = Convert.ToInt32(length / interval) + 1; //_time = new List<double>(); //_value = new List<double>(); _time = new double[size]; _value = new double[size]; for (int i = 0; i < size; i++) { _time[i] = (i * interval); String TempString = function.Replace("x", System.Convert.ToString(_time[i])); Expression e = new Expression(TempString); try { object result = e.Evaluate(); _value[i] = (Convert.ToDouble(result)); } catch(Exception a) { MessageBox.Show("Error caught: " + a.Message); } } SetProperties((FunctionType)type); }
public void IterationTest() { var expr = new Expression("Sin(x)", EvaluateOptions.IgnoreCase | EvaluateOptions.IterateParameters); expr.Parameters["x"] = Enumerable.Range(0, 1000).Select(x => x / Math.PI).ToArray(); foreach(var result in (IList)expr.Evaluate()) Console.WriteLine(result.AsDouble()); }
private void btnCalcul_Click(object sender, EventArgs e) { EvalCalculation evalCalcul = new EvalCalculation(); NCalc.Expression exp = new NCalc.Expression(evalCalcul.RebuildForm(txtInputCalcul.Text).ToString()); rttResultsDisplay.Text = exp.Evaluate().ToString(); }
public RuleEngineRule(string id, string name, string expression, RuleEngineRule parent) { Id = id; Name = name; RuleExpression = expression; Parent = parent; Expression = new Expression(expression); }
public async void Execute(Dictionary<string, object> context) { Update update = context["update"] as Update; CommandEntity commandEntity = context["commandEntity"] as CommandEntity; Expression mathExpression=new Expression(commandEntity.Parameter,EvaluateOptions.IgnoreCase); var message = mathExpression.Evaluate().ToString(); await _bot.SendTextMessage(update.Message.Chat.Id,message); }
public static decimal Evaluate(String input) { NCalc.Expression e = new NCalc.Expression(input); var result = e.Evaluate(); decimal h2 = Decimal.Parse(result.ToString(), System.Globalization.NumberStyles.Any); return(Convert.ToDecimal(h2)); }
public MainWindow() { InitializeComponent(); func = new NCalc.Expression(textBox.Text); perv = new NCalc.Expression(textBox1.Text); a = Convert.ToDouble(textBox2.Text); b = Convert.ToDouble(textBox2_Copy.Text); precision = Convert.ToDouble(textBox2_Copy1.Text); }
private void button_Click(object sender, RoutedEventArgs e) { exp = new NCalc.Expression(function.Text); for (int i = 0; i < vectorX.Length; ++i) { vectorY[i] = calculateFx(vectorX[i]); textBox3.Text += vectorY[i] + " "; } }
public BoundInstruction(InstructionDefinition insn, byte[] bytes, int curOffset, SectionInfo section) { _section = section; _curAbsoluteOffset = curOffset + _section.SectionOffset; this.Instruction = insn; InitializeBoundData(bytes); _boundValues['A'] = curOffset; _pcRelBranchExpr = new Expression("A+o*2"); }
public static IEnumerable <double> UnaryEvaluate(this string expression, string parameterName, Func <double[]> parameterFunc) { expression.ShouldNotBeWhiteSpace("expression"); var expr = new NCalc.Expression(expression, EvaluateOptions.IgnoreCase | EvaluateOptions.IterateParameters); expr.Parameters["x"] = parameterFunc(); return(((IList)expr.Evaluate()).Cast <object>().Select(result => result.AsDouble())); }
public Double Evaluate(List <int> population) { #region Function Variables var op1 = GenerateOperator(); var op2 = GenerateOperator(); var op3 = GenerateOperator(); var op4 = GenerateOperator(); var v1 = GenerateVariable(); var v2 = GenerateVariable(); var v3 = GenerateVariable(); var v4 = GenerateVariable(); var s1 = GenerateSign(); var s2 = GenerateSign(); var s3 = GenerateSign(); var s4 = GenerateSign(); var s5 = GenerateSign(); var s6 = GenerateSign(); var s7 = GenerateSign(); var s8 = GenerateSign(); var s9 = GenerateSign(); var s10 = GenerateSign(); var n1 = RandomFromPop(population); var n2 = RandomFromPop(population); var n3 = RandomFromPop(population); var n4 = RandomFromPop(population); var n5 = RandomFromPop(population); var n6 = RandomFromPop(population); var n7 = RandomFromPop(population); var n8 = RandomFromPop(population); var n9 = RandomFromPop(population); var n10 = RandomFromPop(population); var trig = GenerateTrig(); #endregion var s = $"Pow((Pow({s1}{n1} {v1} , {s2}{n2}) {op1} Pow({s3}{n3} {v2} , {s4}{n4})), {s5}{n5}) {op2} Pow({s6}{n6} {v3} , {s7}{n7}) {op3} Exp({s8}{n8}) {op4} {trig}(Pow({s9}{n9} {v4} , {s10}{n10}))"; s = s.Replace(" x ", "*-7.62"); s = s.Replace(" y ", "*11.43"); s = s.Replace(" z ", "*1.06"); NCalc.Expression e = new NCalc.Expression(s); e.Parameters["x"] = X; e.Parameters["y"] = Y; e.Parameters["z"] = Z; var result = e.Evaluate(); Console.WriteLine($"The function evaluated is {s}"); return(Convert.ToDouble(result)); }
/// <summary> /// Initializes this class. This must be called before calling Execute(). /// </summary> public void Configure(EvaluationControlPointInput evalInput, Expression expression) { this.OutputIsValid = false; this.evalInput = evalInput; this.expression = expression; this.expression.EvaluateFunction += FunctionHandler; SetExpressionBaseParameters((EvaluationInput) evalInput); }
/// <summary> /// Registers a known <see cref="IExpressionFunction"/> against the <paramref name="ncalcExpression"/>. /// </summary> /// <param name="ncalcExpression">A <see cref="NCalc.Expression"/> to register the <see cref="IExpressionFunction"/> for.</param> /// <param name="function">The name of the function to register.</param> public void RegisterFunction(Expression ncalcExpression, string function) { IExpressionFunction type = this.implementingTypes.FirstOrDefault(t => t.FunctionName.Equals(function)); if (type == null) { throw new IndexOutOfRangeException(string.Format(ExceptionMessages.Culture, ExceptionMessages.UnknownCalculationFunction, typeof(IExpressionFunction), function)); } type.Register(ncalcExpression); }
public FnHelper(string expression) { Expression = new Expression(expression, EvaluateOptions.IgnoreCase); //Expression.EvaluateParameter += (name, args) => //{ // if (name == "E") // { // args.Result = Math.E; // } //}; }
public void Evaluate(Expression exp, double a, double b, double tolerance) { addToLog("Starting Regula Falsi Method"); double functionA, functionB, functionX, x, xNew; while (true) { iteration++; // Functions functionA = evaluate(exp, a); functionB = evaluate(exp, b); x = ((a * functionB) - (b * functionA)) / (functionB - functionA); functionX = evaluate(exp, x); // log addToLog(newLine + "Iteration: " + iteration); addToLog("a= " + RoundDigit(a, 4) + tab + "b= " + RoundDigit(b, 4) + tab + "x=" + RoundDigit(x, 4) + tab + tab + "F(a)= " + RoundDigit(functionA, 4) + tab + "F(b): " + RoundDigit(functionB, 4) + tab + "F(x): " + RoundDigit(functionX, 4) + tab); // swapping: doesnt matter, no rule, try a 50 times, then b if (iteration > 50) { b = x; functionB = functionX; } else { a = x; functionA = functionX; } addToLog("x swaps with " + ((iteration > 50) ? "b" : "a")); xNew = ((a * functionB) - (b * functionA)) / (functionB - functionA); // check tolerance bool withinTolerance = inTolerance(tolerance, x, xNew); if (withinTolerance) break; x = xNew; if (iteration >= 350) { addToLog("Iteration threshold reached, STOPPING!"); break; } } addToLog("ROOT FOUND: " + x); }
private void Equals_Click(object sender, RoutedEventArgs e) { try { expression = expression.EndsWith(".") ? expression + "0" : expression; string validResult = new NCalc.Expression(expression).Evaluate().ToString(); DisplayToResult(); } catch (Exception ex) { } }
private void ProcessFormula() { Expression e; try { e = new Expression( FormulaString.ToLower() .Replace(" and ", "+").Replace("&&", "+") .Replace(" or ", "+").Replace("||", "+"), EvaluateOptions.IgnoreCase); } catch (Exception ex) { Error(ex.Message); return; } if (e.HasErrors()) { Error(e.Error); return; } var parameters = new List <string>(); var paramSet = new HashSet <string>(); e.EvaluateParameter += delegate(string name, ParameterArgs args) { if (!paramSet.Contains(name) && !reservedParamNames.Contains(name)) { paramSet.Add(name); parameters.Add(name); } args.Result = 0; }; try { e.Evaluate(); } catch { } InPortData.Clear(); foreach (var p in parameters) { InPortData.Add(new PortData(p, "variable")); } RegisterInputPorts(); ClearError(); }
public double evaluate(Expression exp, double value) { exp.Parameters["x"] = value; Object EvaluatedExpression = exp.Evaluate(); double result = double.Parse(EvaluatedExpression.ToString()); addToLog("Evaluating: x=" + RoundDigit(value, 4) + tab + "Result: " + RoundDigit(result, 4)); return result; }
public static bool IsIgnoredDecl(IReadOnlyCollection<string> ifStack, IReadOnlyCollection<Definition> defns) { foreach (var s in ifStack) { try { Action<string, FunctionArgs> evalFunc = null; Action<string, ParameterArgs> evalParam = null; evalFunc = (name, args) => { var def = defns.FirstOrDefault(d => d.Identifier == name && d.Arguments != null && d.Arguments.Count == args.Parameters.Length); if (def != null) { var e2 = new Expression(def.Replacement); for (int i = 0; i < def.Arguments.Count; ++i) e2.Parameters.Add(def.Arguments[i], args.Parameters[i].Evaluate()); e2.EvaluateFunction += new EvaluateFunctionHandler(evalFunc); e2.EvaluateParameter += new EvaluateParameterHandler(evalParam); args.Result = e2.Evaluate(); } }; evalParam = (name, args) => { var def = defns.FirstOrDefault(d => d.Identifier == name && d.Arguments == null); if (def != null) { var e2 = new Expression(def.Replacement); e2.EvaluateFunction += new EvaluateFunctionHandler(evalFunc); e2.EvaluateParameter += new EvaluateParameterHandler(evalParam); args.Result = e2.Evaluate(); } }; var e = new Expression(s); e.EvaluateFunction += new EvaluateFunctionHandler(evalFunc); e.EvaluateParameter += new EvaluateParameterHandler(evalParam); var result = e.Evaluate(); if (!Convert.ToBoolean(result)) return true; } catch { // Empty catch, this is non-trivial, just print it out. } } return false; }
public static object Evalulate(JToken token, string expression) { var e = new Expression(expression); e.EvaluateParameter += (name, args) => { args.Result = GetValue(token, name); args.HasResult = true; }; return e.Evaluate(); }
public MainWindow() { InitializeComponent(); methodType = 0; e1 = new NCalc.Expression(textBox1.Text); e2 = new NCalc.Expression(textBox2.Text); Style noSpaceStyle = new Style(typeof(Paragraph)); noSpaceStyle.Setters.Add(new Setter(Paragraph.MarginProperty, new Thickness(0))); richTextBox.Resources.Add(typeof(Paragraph), noSpaceStyle); }
public MainWindow() { InitializeComponent(); exp = new NCalc.Expression(function.Text); string[] xValues = textBox1.Text.Split(' '); vectorX = new double[xValues.Length]; vectorY = new double[xValues.Length]; for (int i = 0; i < xValues.Length; ++i) { vectorX[i] = Convert.ToDouble(xValues[i]); } }
/// Rules // a & b must have opposite signs // c = (a+b)/2 // f(c) replaces negative f(a) or f(b) public void Evaluate(Expression function, double a, double b, double tolerance) { addToLog("Starting Bisection Method"); double cNew, functionA, functionB, functionC; double c = (a + b) / 2; int iteration = 0; // Calculate F(a,b,c) until tolerance is reached while (true) { iteration++; // Functions functionA = evaluate(function, a); functionB = evaluate(function, b); functionC = evaluate(function, c); // log addToLog(newLine + "Iteration " + iteration); addToLog("a= " + RoundDigit(a, 4) + tab + "b= " + RoundDigit(b, 4) + tab + "c= " + RoundDigit(c, 4) + tab + tab + "F(a)= " + RoundDigit(functionA, 4) + tab + "F(b): " + RoundDigit(functionB, 4) + tab + "F(c): " + RoundDigit(functionC, 4)); /// Rule /// // c value replaces either a or b depending on same sign of f(a) or f(b) if (functionC < 0 && functionA < 0) a = c; else b = c; addToLog("c swaps with " + ((functionC < functionB) ? "a" : "b")); // calc. new c cNew = (a + b) / 2; // check tolerance bool withinTolerance = inTolerance(tolerance, c, cNew); if (withinTolerance) break; c = cNew; if (iteration >= 350) { addToLog("Iteration threshold reached, STOPPING!"); break; } } addToLog("ROOT FOUND: " + c); }
public static Object CalculateValue(String key, Object rawValue) { Object returnValue = rawValue; if (ValueRecalculation.ContainsKey(key)) { var szExpress = ValueRecalculation[key].Replace("x", rawValue.ToString()); var express = new NCalc.Expression(szExpress); decimal tmp = Convert.ToDecimal(express.Evaluate()); returnValue = Math.Round(tmp, 2); } return(returnValue); }
/// <summary> /// Initializes this class. /// </summary> public void Configure(EvaluationCurveInput evalInput, List<XyPoint<double>> controlPointValues, Expression expression) { this.OutputIsValid = false; this.evalInput = evalInput; this.controlPointValues = controlPointValues; this.expression = expression; this.expression.EvaluateFunction += FunctionHandler; SetExpressionBaseParameters((EvaluationInput)evalInput); SetExpressionCurveParameters(this.evalInput, this.expression); }
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { try { string val = value.ToString().Replace(',', '.'); NCalc.Expression e = new NCalc.Expression(val); return(e.Evaluate()); } catch (Exception) { return(0); } }
private void Dot_Click(object sender, RoutedEventArgs e) { string expDot = expression.EndsWith(".") ? expression : expression + ".0"; try { string validDot = new NCalc.Expression(expDot).Evaluate().ToString(); expression += "."; DisplayToTextBox(); } catch (Exception ex) { //If errors don't to do Console.WriteLine(ex.Message.ToString()); } }
//########################################################################## #region Methods //-------------------------------------------------------------------------- public void ValueTextChanged() { float value = 0f; try { var exp = new NCalc.Expression(ValueText); var obj = exp.Evaluate(); if (obj is double) { value = (float)(double)obj; } else if (obj is int) { value = (float)(int)obj; } else if (obj is bool) { value = (bool)obj ? 1 : 0; } else { value = (float)obj; } } catch (Exception) { HasError = true; return; } if (UseIntegers) { value = (int)value; } if (value < MinValue || value > MaxValue) { HasError = true; return; } cameFromUs = true; HasError = false; Value = value; }
/// <summary> /// /// </summary> /// <param name="element"></param> /// <param name="evp"></param> public override void Visit(IFStatement element, EvaluationParam evp) { NCalc.Expression e = new NCalc.Expression(element.Text); e.EvaluateFunction += delegate(string name, FunctionArgs args) { if (name.ToLower() == "mod") { args.Result = (int)args.Parameters[0].Evaluate() % (int)args.Parameters[1].Evaluate(); } }; var a = e.Evaluate(); result = new Result(); result.Value = a; // throw new NotImplementedException(); }
static void Main(string[] args) { //ExpTreeMap(10000); //ExpTreeMap(10000); //ExpTreeMap(10000); int a1 = 4, a2 = 5; string exp1 = "[a1]*[Pi]"; NCalc.Expression e = new NCalc.Expression(exp1); e.Parameters["a1"] = a1; e.Parameters["a2"] = a2; e.EvaluateParameter += delegate(string name, ParameterArgs arg) { if (name == "Pi") { arg.Result = 2; } }; var r = e.Evaluate(); //string exp2 = $"tag(\"tag1\",123)"; //NCalc.Expression e2 = new NCalc.Expression(exp2); //e2.EvaluateFunction += (name, arg) => //{ // if(name== "tag") // { // var p= arg.Parameters; // } //}; //e2.Evaluate(); Console.ReadLine(); //IProducerConsumerCollection //ConcurrentBag BlockingCollection }
private void Grid_Click(object sender, RoutedEventArgs e) { // обработчик работает только для кнопок Button btn = e.Source as Button; if (btn == null) { return; } // обработчик работает только для кнопок у которых есть значение (контент) string value = btn.Content.ToString(); if (String.IsNullOrEmpty(value)) { return; } switch (value) { // стираем текстовое поле case "C": TextBoxMain.Text = "0"; break; // считаем выражение с помощью библиотеки NCalc // https://ncalc.codeplex.com/ case "=": try { NCalc.Expression exp = new NCalc.Expression(TextBoxMain.Text); TextBoxMain.Text = exp.Evaluate().ToString(); } catch { TextBoxMain.Text = "Error"; } break; // добавялем новое значение в текстовое поле и удаляем стартовый 0 default: TextBoxMain.Text = TextBoxMain.Text.TrimStart('0') + value; break; } }
private void BuildExpressionGraph(SingleSeriesChart chart) { var expr = new NCalc.Expression(Expression, EvaluateOptions.IgnoreCase | EvaluateOptions.IterateParameters); var step = (Upper - Lower) / VarCount; var x = EnumerableTool.Step(Lower, Upper, step).ToArray(); expr.Parameters["x"] = x; var y = ((IEnumerable)expr.Evaluate()).ToListUnsafe <double>(); for (var i = 0; i < x.Length; i++) { chart.SetElements.Add(new ValueSetElement(y[i]) { Label = x[i].ToString("#.0") }); } }
private void Positive_Negative_Click(object sender, RoutedEventArgs e) { try { //1. check chuỗi hợp lệ string validExp = new NCalc.Expression(expression).Evaluate().ToString(); //2. clone chuỗi string cloneExp = expression; // 3. 23+(-14)/9-9*2 cloneExp = cloneExp .Replace("(-", ":") //thay thế(- thành dấu : 23+(-14)/9 => 23+:14)/9-9*2 .Replace(")", ""); //xóa dấu ) 23+:14) => 23+:14/9-9*2 cloneExp = cloneExp .Replace("*", ",") //thay dấu * thành dấu , 23+:14/9-9*2 => 23+:14/9-9,2 .Replace("/", ",") //thay dấu * thành dấu , 23+:14/9-9,2 => 23+:14,9-9,2 .Replace("+", ",") //thay dấu * thành dấu , 23+:14,9-9,2 => 23,:14,9-9,2 .Replace("-", ","); //thay dấu * thành dấu , 23,:14,9-9,2 => 23,:14,9,9,2 string[] exp = cloneExp.Split(','); // cắt chuỗi string thành array string phân cách = dấu , 23,:14,9,9,2 => [23, :14, 9, 9, 2] string lastString = exp[exp.Length - 1]; // lấy ra string cuối cùng. 2 float lastNumber = float.Parse(exp[exp.Length - 1].Replace(":", "-")); //Thay dấu : thành dấu -. Và parse string sang float int length = lastString.Length; // lấy độ dài của string cuối cùng if (lastNumber > 0) { //Số dương thì chuyển thành số âm = cách thay thế số cuối cùng của chuỗi expression = số hiện tại thêm đóng mở ngoặc và dấu -. //23+(-14)/9-9*2 => 23+(-14)/9-9*(-2) expression = expression.Substring(0, expression.Length - length) + "(-" + lastNumber + ")"; } else { //Số âm thì chuyển thành số dương = cách thay thế số cuối cùng của chuỗi expression = và số hiện tại. Xóa dấu đóng mở ngoặc và dấu - //23+(-14)/9-9*(-2) => 23+(-14)/9-9*2 expression = expression.Substring(0, expression.Length - (length + 2)) + lastNumber.ToString().Replace("-", ""); } DisplayToTextBox(); } catch (Exception ex) { //lỗi xảy ra không thao tác gì Console.WriteLine(ex.Message.ToString()); } }
public static decimal LeerConcepto(string conceptvalue, int idx) { if (conceptvalue == string.Empty || conceptvalue == null) { return(0); } var conceptvaluex = conceptvalue.Replace(" ", ""); var divconcept = conceptvaluex.Split('*', '+', '-', '/', '(', ')'); string valorconvertido = conceptvaluex; nominaEntities paraconcepto = new nominaEntities(); foreach (var item in divconcept) { if (item.Contains('$')) { var y = LeerCampo(item, idx); valorconvertido = valorconvertido.Replace(item, y); } if (item.Contains('@')) { var itemn = item.Remove(0, 1); var j = EjecutarProc(itemn, idx.ToString()); valorconvertido = valorconvertido.Replace(item, j); } } valorconvertido = valorconvertido.Replace(',', '.'); NCalc.Expression e = new NCalc.Expression(valorconvertido); decimal evaluation = 0; try { evaluation = decimal.Parse(e.Evaluate().ToString()); } catch (System.ArgumentException x) { Datos.Msg("Error en Concepto Numero " + idx.ToString() + ". El parametro " + x.ParamName + " no existe o esta mal escrito."); } return(Decimal.Round(evaluation, 2));; }
private void Result() { if (tb_result.Text.Length <= 0) { Debug.WriteLine("Operation Not Allowed"); return; } String lastChar = tb_result.Text.Substring(tb_result.Text.Length - 1, 1); if (lastChar.Equals("/") || lastChar.Equals("*") || lastChar.Equals("+") || lastChar.Equals("-")) { Debug.WriteLine("Operation Not Allowed"); return; } NCalc.Expression e = new NCalc.Expression(tb_result.Text); tb_result.Text = e.Evaluate().ToString(); // clears displays next evaluation resultCalculated = true; }
private void Calculate() { try { string tmp = eText; if (LastSymbol == ".") { tmp += "0"; } int amount = 0; for (int i = 0; i < tmp.Length; i++) { if (tmp[i] == '(') { amount++; } else if (tmp[i] == ')') { amount--; } } for (int i = 0; i < amount; i++) { tmp += ")"; } expression = new NCalc.Expression(tmp); expression.Parameters["p"] = 3.14; expression.Parameters["e"] = 2.71828; Answer.Text = expression.Evaluate().ToString().Replace(",", "."); } catch { Answer.Text = ""; } }
private void explicitMethod(uint rank) { TextRange txt = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); txt.Text = ""; funct = new NCalc.Expression(textBox.Text); exact = new NCalc.Expression(textBox1.Text); double a = Convert.ToDouble(textBox3.Text); double b = Convert.ToDouble(textBox4.Text); double h = Convert.ToDouble(textBox5.Text); txt.Text += "Екстраполяційний Метод Адамса:\n"; txt.Text += String.Format("{0}\t{1}\t\t\t{2}\t\t\t{3}\n", "xi", "yi*", "yi", "yi(точне)"); double x = a; uint quantity = 0; double k1 = 0, k2 = 0, k3 = 0, k4 = 0; int steps = (int)((b - a) / h); double[] vals = new double[steps + 1]; vals[0] = Convert.ToDouble(textBox2.Text); txt.Text += String.Format("{0}\t{1}\t{2}\n", x, vals[0], calculateExact(x)); switch (rank) { case 2: { //#####P=2 for (int i = 1; i < 2; ++i) { k1 = h * calculateFunction(x, vals[i - 1]); k2 = h * calculateFunction(x + h / 3, vals[i - 1] + k1 / 3); k3 = h * calculateFunction(x + 2 * h / 3, vals[i - 1] - k1 / 3 + k2); k4 = h * calculateFunction(x + h, vals[i - 1] + k1 - k2 + k3); vals[i] = vals[i - 1] + (k1 + 3 * k2 + 3 * k3 + k4) / 8; x += h; txt.Text += String.Format("{0}\t{1}\t{2}\n", x, vals[i], calculateExact(x)); ++quantity; } for (int i = 2; i <= steps; ++i) { vals[i] = vals[i - 1] + h * (1.5 * calculateFunction(x, vals[i - 1]) - 0.5 * calculateFunction(x - h, vals[i - 2])); x += h; txt.Text += String.Format("{0}\t{1}\t{2}\n", x, vals[i], calculateExact(x)); ++quantity; } break; } case 3: { //#####P=3 for (int i = 1; i < 3; ++i) { k1 = h * calculateFunction(x, vals[i - 1]); k2 = h * calculateFunction(x + h / 3, vals[i - 1] + k1 / 3); k3 = h * calculateFunction(x + 2 * h / 3, vals[i - 1] - k1 / 3 + k2); k4 = h * calculateFunction(x + h, vals[i - 1] + k1 - k2 + k3); vals[i] = vals[i - 1] + (k1 + 3 * k2 + 3 * k3 + k4) / 8; x += h; txt.Text += String.Format("{0}\t{1}\t{2}\n", x, vals[i], calculateExact(x)); ++quantity; } for (int i = 3; i <= steps; ++i) { vals[i] = vals[i - 1] + (h / 12) * (23 * calculateFunction(x, vals[i - 1]) - 16 * calculateFunction(x - h, vals[i - 2]) + 5 * calculateFunction(x - 2 * h, vals[i - 3])); x += h; txt.Text += String.Format("{0}\t{1}\t{2}\n", x, vals[i], calculateExact(x)); ++quantity; } break; } case 4: { //#####P=4 for (int i = 1; i < 4; ++i) { k1 = h * calculateFunction(x, vals[i - 1]); k2 = h * calculateFunction(x + h / 3, vals[i - 1] + k1 / 3); k3 = h * calculateFunction(x + 2 * h / 3, vals[i - 1] - k1 / 3 + k2); k4 = h * calculateFunction(x + h, vals[i - 1] + k1 - k2 + k3); vals[i] = vals[i - 1] + (k1 + 3 * k2 + 3 * k3 + k4) / 8; x += h; txt.Text += String.Format("{0}\t{1}\t{2}\n", x, vals[i], calculateExact(x)); ++quantity; } for (int i = 4; i <= steps; ++i) { vals[i] = vals[i - 1] + (h / 24) * (55 * calculateFunction(x, vals[i - 1]) - 59 * calculateFunction(x - h, vals[i - 2]) + 37 * calculateFunction(x - 2 * h, vals[i - 3]) - 9 * calculateFunction(x - 3 * h, vals[i - 4])); x += h; txt.Text += String.Format("{0}\t{1}\t{2}\n", x, vals[i], calculateExact(x)); ++quantity; } break; } case 5: { //#####P=5 for (int i = 1; i < 5; ++i) { k1 = h * calculateFunction(x, vals[i - 1]); k2 = h * calculateFunction(x + h / 3, vals[i - 1] + k1 / 3); k3 = h * calculateFunction(x + 2 * h / 3, vals[i - 1] - k1 / 3 + k2); k4 = h * calculateFunction(x + h, vals[i - 1] + k1 - k2 + k3); vals[i] = vals[i - 1] + (k1 + 3 * k2 + 3 * k3 + k4) / 8; x += h; txt.Text += String.Format("{0}\t{1}\t{2}\n", x, vals[i], calculateExact(x)); ++quantity; } for (int i = 5; i <= steps; ++i) { vals[i] = vals[i - 1] + (h / 720) * (1901 * calculateFunction(x, vals[i - 1]) - 2774 * calculateFunction(x - h, vals[i - 2]) + 2616 * calculateFunction(x - 2 * h, vals[i - 3]) - 1274 * calculateFunction(x - 3 * h, vals[i - 4]) + 251 * calculateFunction(x - 4 * h, vals[i - 5])); x += h; txt.Text += String.Format("{0}\t{1}\t{2}\n", x, vals[i], calculateExact(x)); ++quantity; } break; } } txt.Text += String.Format("Кількість ітерацій: {0}\n", quantity); txt.Text += String.Format("Точність(|y(b)-y*(b)|): {0}", Math.Abs(vals[steps] - calculateExact(x))); }
public void Square() { var expr = new Expression("[t]*[t]"); expr.Parameters["t"] = 2; var result = expr.Evaluate(); Assert.AreEqual(4, result); }