Beispiel #1
0
        public static double Calculate(ref List <string> expression)
        {
            for (int i = 0; i < expression.Count; ++i)
            {
                string atom = expression[i];
                if (!(atom.Contains('+') ||
                      atom.Contains('-') ||
                      atom.Contains('*') ||
                      atom.Contains('/') ||
                      atom.Contains('(') ||
                      atom.Contains(')')))
                {
                    try
                    {
                        expression[i] = AtomToValue(atom).ToString();
                    }
                    catch (NoValueForAtom e)
                    {
                        expression[i] = "";
                        expression    = new List <string>();
                        expression.Add("0");
                    }
                }
            }
            string               sExpression        = MakeStringFromList(expression);
            PreparedExpression   preparedExpression = ToolsHelper.Parser.Parse(sExpression);
            CompiledExpression   compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);
            List <VariableValue> variables          = new List <VariableValue>();

            return(ToolsHelper.Calculator.Calculate(compiledExpression, variables));
        }
Beispiel #2
0
        /// <summary>
        /// Нажатие на кнопку вычисления
        /// </summary>
        /// <param name="sender">объект</param>
        /// <param name="e">событие</param>
        private void clickOnBtn(object sender, RoutedEventArgs e)
        {
            try
            {
                // Парсинг строки
                PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(textBox.Text);
                // Компиляция распарсеных данных
                CompiledExpression compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);
                // Creating list of variables specified
                List <VariableValue> variables = new List <VariableValue>();

                try
                {
                    // Рассчёт
                    double res = ToolsHelper.Calculator.Calculate(compiledExpression, variables);
                    // Отображение результата
                    result.Content = String.Format("Результат: {0}", res);
                }
                catch { };
            }
            catch (CompilerSyntaxException ex)
            {
                result.Content = String.Format("Ошибка синтаксиса: {0}", ex.Message);
            }
            catch (MathProcessorException ex)
            {
                result.Content = String.Format("Ошибка: {0}", ex.Message);
            }
        }
Beispiel #3
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Парсим строку с математическим выражением
                PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(textBox.Text);
                // Компиляция распарсеных данных
                CompiledExpression compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);
                // Создание списка переменных
                List <VariableValue> variables = new List <VariableValue>();

                // Рассчёт
                double res = ToolsHelper.Calculator.Calculate(compiledExpression, variables);
                // Отображение результата
                result.Content = String.Format("Результат: {0}", res);
            }
            catch (CompilerSyntaxException ex)
            {
                result.Content = String.Format("Ошибка синтаксиса: {0}", ex.Message);
            }
            catch (MathProcessorException ex)
            {
                result.Content = String.Format("Ошибка: {0}", ex.Message);
            }
            catch (ArgumentException)
            {
                result.Content = "Ошибка в входных данных";
            }
        }
        private double EvaluateExpressionWithVariables(string expression, List <VariableValue> variables)
        {
            try
            {
                // Compiling an expression
                PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(expression);
                CompiledExpression compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);


                // Do it !
                double res = ToolsHelper.Calculator.Calculate(compiledExpression, variables);

                return(res);
            }
            catch (CompilerSyntaxException ex)
            {
                //MessageBox.Show(String.Format("Compiler syntax error: {0}", ex.Message));
                throw;
            }
            catch (MathProcessorException ex)
            {
                //MessageBox.Show(String.Format("Error: {0}", ex.Message));
                throw;
            }
            catch (ArgumentException)
            {
                //MessageBox.Show("Error in input data.");
                throw;
            }
            catch (Exception)
            {
                //MessageBox.Show("Unexpected exception.");
                throw;
            }
        }
Beispiel #5
0
        ///////////////////////////////////////////

        /// <summary>
        /// Prepares expression for faster calculation. Use when you need calculate one expression with different parameters many times.
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="parameterNames"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public PreparedExpression Prepare(string expression, ICollection <string> parameterNames, out string error)
        {
            error = null;

            try
            {
                Dictionary <string, int> parameterNamesLowerCase = null;
                //Set<string> parameterNamesLowerCase = null;
                if (parameterNames != null)
                {
                    parameterNamesLowerCase = new Dictionary <string, int>(parameterNames.Count);
                    foreach (string parameterName in parameterNames)
                    {
                        parameterNamesLowerCase[parameterName.ToLower()] = 0;
                    }
                }

                List <Symbol> symbols = Separate(expression, parameterNamesLowerCase);
                List <Symbol> postfix = ConvertToPostfixNotation(symbols);

                PreparedExpression preparedExpression = new PreparedExpression(this, postfix);
                return(preparedExpression);
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(null);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Матиматическое вычисление выражения
        /// </summary>
        /// <param name="variables">Список параметров</param>
        /// <param name="Expression">Текст выражения</param>
        /// <returns>Результат вычисления</returns>
        public static double Calc(List <VariableValue> variables, string Expression)
        {
            double result = 0;


            try
            {
                // Compiling an expression
                PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(Expression);
                CompiledExpression compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);
                // Optimizing an expression
                CompiledExpression optimizedExpression = ToolsHelper.Optimizer.Optimize(compiledExpression);
                // Creating list of variables specified
                //    List<VariableValue> variables = new List<VariableValue>();

                //    double firstValue;
                //    if (!Double.TryParse(textBoxValue1.Text, out firstValue))
                //    {
                //        MessageBox.Show("Error converting first variable value.");
                //        return;
                //    }
                //    variables.Add(new VariableValue(firstValue, textBoxVariable1.Text));

                //    double secondValue;
                //    if (!Double.TryParse(textBoxValue2.Text, out secondValue))
                //    {
                //        MessageBox.Show("Error converting second variable value.");
                //        return;
                //    }
                //    variables.Add(new VariableValue(secondValue, textBoxVariable2.Text));

                // Do it !
                result = ToolsHelper.Calculator.Calculate(compiledExpression, variables);
                // Show the result.
                //    MessageBox.Show(String.Format("Result: {0}\nOptimized: {1}", res, ToolsHelper.Decompiler.Decompile(optimizedExpression)));
            }
            catch (CompilerSyntaxException ex)
            {
                Errors.Add("Ошибка компиляции выражения:" + ex.Message);
            }
            catch (MathProcessorException ex)
            {
                Errors.Add("Ошибка:" + ex.Message);
            }
            catch (ArgumentException)
            {
                Errors.Add("Ошибка переданных параметров");
            }
            catch (Exception)
            {
                Errors.Add("Неизвестная ошибка");
                throw;
            }


            return(result);
        }
Beispiel #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Проверка входных данных.
            int   isOkay = 0;
            float s      = 0;

            float[] inputs = new float[10];
            float   from = 1, to = -1, step = 0;

            if (!(float.TryParse(FromX.Text.Replace(".", ","), out from) && float.TryParse(ToX.Text.Replace(".", ","), out to))) //|| from > to)
            {
                isOkay = 1;
            }
            else
            if (from > to)
            {
                isOkay = 2;
            }
            else
            if (!float.TryParse(Step.Text.Replace(".", ","), out step))
            {
                isOkay = 3;
            }
            else
            if (step > to - from)
            {
                isOkay = 4;
            }
            //Проверка на правильность ввода функции.
            try
            {
                preparedExpression = ToolsHelper.Parser.Parse(FuncBox.Text.Replace(" ", ""));
                compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);
                F = (xx) => { vars[0] = new VariableValue(xx, VarName.Text); return((float)ToolsHelper.Calculator.Calculate(compiledExpression, vars)); };
                F(0.332f);
            }
            catch (Exception)
            {
                isOkay = 5;
            }
            //Вывод сообщения об ошибке или построение графика.
            switch (isOkay)
            {
            case 0: PackIntoListBox(VarName.Text, FuncBox.Text, from, to, step); Calculate(from, to, step); break;

            case 1: MessageBox.Show("Неверно введены границы интервала.", "Ошибка.", MessageBoxButtons.OK); break;

            case 2: MessageBox.Show("Левая граница должна быть меньше правой границы.", "Ошибка.", MessageBoxButtons.OK); break;

            case 3: MessageBox.Show("Неверно введен шаг.", "Ошибка.", MessageBoxButtons.OK); break;

            case 4: MessageBox.Show("Длина шага не должна превышать длину интервала.", "Ошибка.", MessageBoxButtons.OK); break;

            case 5: MessageBox.Show("Неверно введена функция или название параметра.", "Ошибка.", MessageBoxButtons.OK); break;
            }
        }
        public DecompiledExpressionItem(bool isComplex, PreparedExpression expression, Operation lastOperation)
            : this(isComplex, expression)
        {
            if (lastOperation == null)
            {
                throw new ArgumentNullException("lastOperation");
            }

            this.lastOperation = lastOperation;
        }
        public DecompiledExpressionItem(bool isComplex, PreparedExpression expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            this.isComplex  = isComplex;
            this.expression = expression;
        }
Beispiel #10
0
        private async Task <double> H(double x, string function)
        {
            List <VariableValue> variables = new List <VariableValue>
            {
                new VariableValue(x, "x")
            };
            PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(function);
            CompiledExpression compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);

            return(await Task.FromResult(ToolsHelper.Calculator.Calculate(compiledExpression, variables)));
        }
Beispiel #11
0
        static public double calculate(string input, double value)
        {
            PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(input);

            CompiledExpression compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);

            List <VariableValue> variables = new List <VariableValue>();

            variables.Add(new VariableValue(value, "x"));
            double res = ToolsHelper.Calculator.Calculate(compiledExpression, variables);

            return(res);
        }
Beispiel #12
0
        void UnpackFromListBox(int index)
        {
            //Получение значения из текущего элемента списка.
            string[] ins    = listBox1.Items[index].ToString().Replace(" ", "").Split('|');
            string   varstr = ins[0].Substring(ins[0].IndexOf("(") + 1, ins[0].IndexOf(")") - ins[0].IndexOf("(") - 1);

            ins[0]             = ins[0].Remove(0, ins[0].IndexOf('=') + 1);
            FuncBox.Text       = ins[0]; FromX.Text = ins[1]; ToX.Text = ins[2]; Step.Text = ins[3];
            preparedExpression = ToolsHelper.Parser.Parse(ins[0]);
            compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);

            F = (xx) => { vars[0] = new VariableValue(xx, varstr); return((float)ToolsHelper.Calculator.Calculate(compiledExpression, vars)); };
        }
Beispiel #13
0
 private bool checkExpression(string function)
 {
     try
     {
         PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(function);
         return(true);
     }
     catch (CompilerSyntaxException ex)
     {
         System.Windows.MessageBox.Show(String.Format("Неверно задана функция: {0}", ex.Message));
     }
     return(false);
 }
        private double f(double x, double y)
        {
            PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(Integral);

            CompiledExpression compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);

            List <VariableValue> variables = new List <VariableValue>();

            variables.Add(new VariableValue(x, "x"));
            variables.Add(new VariableValue(y, "y"));
            double res = ToolsHelper.Calculator.Calculate(compiledExpression, variables);

            return(res);
        }
        private Double CalcExp(string exp)
        {
            try
            {
                exp = exp.Replace(" ", "").Replace("\r", "").Replace("\n", "");
                // Compiling an expression
                PreparedExpression preparedExpression  = ToolsHelper.Parser.Parse(exp);
                CompiledExpression compiledExpression  = ToolsHelper.Compiler.Compile(preparedExpression);
                CompiledExpression optimizedExpression = ToolsHelper.Optimizer.Optimize(compiledExpression);
                // Creating list of variables specified
                List <VariableValue> variables = new List <VariableValue>();


                foreach (KeyValuePair <string, string> pair in GroupValue)
                {
                    double val;
                    string var = pair.Value.Replace(" ", "").Replace("\r", "").Replace("\n", "").Replace(".", System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator).Replace(",", System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator);
                    if (!Double.TryParse(var, out val))
                    {
                        Log($"{pair.Key} = {var} - не число");
                    }
                    else
                    {
                        variables.Add(new VariableValue(val, pair.Key));
                    }
                }
                return(ToolsHelper.Calculator.Calculate(compiledExpression, variables));
            }
            catch (CompilerSyntaxException ex)
            {
                Log(String.Format("Compiler syntax error: {0}", ex.Message));
            }
            catch (MathProcessorException ex)
            {
                Log(String.Format("Error: {0}", ex.Message));
            }
            catch (ArgumentException)
            {
                Log("Error in input data.");
            }
            catch (Exception)
            {
                Log("Unexpected exception.");
            }

            return(Double.NaN);
        }
Beispiel #16
0
 private bool trytocalculateExpression()
 {
     try
     {
         PreparedExpression   preparedExpression  = ToolsHelper.Parser.Parse(function.Text.Replace(',', '.').ToLower());
         CompiledExpression   compiledExpression  = ToolsHelper.Compiler.Compile(preparedExpression);
         CompiledExpression   optimizedExpression = ToolsHelper.Optimizer.Optimize(compiledExpression);
         List <VariableValue> variables           = new List <VariableValue>();
         variables.Add(new VariableValue(0, "x"));
         double res = ToolsHelper.Calculator.Calculate(compiledExpression, variables);
     }
     catch
     {
         return(false);
     }
     return(true);
 }
Beispiel #17
0
        private double calculate(string input, Hashtable args)
        {
            int n = (int)NewtonUpDown.Value;

            PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(input);

            CompiledExpression compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);

            List <VariableValue> variables = new List <VariableValue>();

            for (int i = 0; i < n; ++i)
            {
                variables.Add(new VariableValue((double)args[variable[i].ToString()], variable[i].ToString()));
            }
            double res = ToolsHelper.Calculator.Calculate(compiledExpression, variables);

            return(res);
        }
Beispiel #18
0
        private double[] calc(string function, int step, double min, double max, out double[] xData)
        {
            xData = new double[step];
            double[] yData = new double[step];
            try
            {
                double delta = (max - min) / step;
                double tmp   = min;
                List <VariableValue> values = new List <VariableValue>();

                for (int i = 0; i < step; i++)
                {
                    values.Add(new VariableValue(tmp, "x"));

                    xData[i] = tmp;

                    PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(function);
                    CompiledExpression compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);
                    yData[i] = ToolsHelper.Calculator.Calculate(compiledExpression, values);
                    values.Clear();
                    tmp += delta;
                }
                return(yData);
            }
            catch (MathProcessorException ex)
            {
                System.Windows.MessageBox.Show(String.Format("Error: {0}", ex.Message));
            }
            catch (ArgumentException)
            {
                System.Windows.MessageBox.Show("Error in input data.");
            }
            catch (ArithmeticException ex)
            {
                System.Windows.MessageBox.Show(String.Format("Error: {0}", ex.Message));
            }
            catch (Exception)
            {
                System.Windows.MessageBox.Show("Unexpected exception.");
                throw;
            }
            isError = true;
            return(null);
        }
Beispiel #19
0
        // взято с http://habrahabr.ru/blogs/net/50158/
        private double calculateExpression(double firstValue)
        {
            /*try
             * {*/
            // Compiling an expression
            PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(function.Text.Replace(',', '.').ToLower());
            CompiledExpression compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);
            // Optimizing an expression
            CompiledExpression optimizedExpression = ToolsHelper.Optimizer.Optimize(compiledExpression);
            // Creating list of variables specified
            List <VariableValue> variables = new List <VariableValue>();


            variables.Add(new VariableValue(firstValue, "x"));

            // Do it !
            double res = ToolsHelper.Calculator.Calculate(compiledExpression, variables);

            return(res);

            /*}
             * catch (CompilerSyntaxException ex)
             * {
             *  MessageBox.Show(String.Format("Compiler syntax error: {0}", ex.Message));
             *
             * }
             * catch (MathProcessorException ex)
             * {
             *  MessageBox.Show(String.Format("Error: {0}", ex.Message));
             *
             * }
             * catch (ArgumentException)
             * {
             *  MessageBox.Show("Error in input data.");
             *
             * }
             * catch (Exception)
             * {
             *  MessageBox.Show("Unexpected exception.");
             *  throw;
             * }*/
            //return 0.0;
        }
        public ClassFormulaParsing(string formula, ELW.Library.Math.Tools.VariableValue[] args)
        {
            try
            {
                // Compiling an expression
                PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(formula);
                CompiledExpression compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);
                // Optimizing an expression
                CompiledExpression optimizedExpression = ToolsHelper.Optimizer.Optimize(compiledExpression);
                // Creating list of variables specified
                List <VariableValue> variables = new List <VariableValue>();

                foreach (VariableValue arg in args)
                {
                    variables.Add(arg);
                }

                // Do it !
                double res = ToolsHelper.Calculator.Calculate(compiledExpression, variables);
                // Show the result.
                Console.WriteLine(String.Format("Result: {0}\nOptimized: {1}", res, ToolsHelper.Decompiler.Decompile(optimizedExpression)));
            }
            catch (CompilerSyntaxException ex)
            {
                Console.WriteLine(String.Format("Compiler syntax error: {0}", ex.Message));
            }
            catch (MathProcessorException ex)
            {
                Console.WriteLine(String.Format("Error: {0}", ex.Message));
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Error in input data.");
            }
            catch (Exception)
            {
                Console.WriteLine("Unexpected exception.");
                throw;
            }
        }
Beispiel #21
0
        /// <summary>
        /// Calculates expression. Example: "1 + (2 * 3)", "5 * x + y".
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="parameters"></param>
        /// <param name="result"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool Calculate(string expression, Dictionary <string, double> parameters, out double result,
                              out string error)
        {
            error  = null;
            result = 0;

            ICollection <string> parameterNames = null;

            if (parameters != null)
            {
                parameterNames = parameters.Keys;
            }

            PreparedExpression preparedExpression = Prepare(expression, parameterNames, out error);

            if (preparedExpression == null)
            {
                return(false);
            }

            return(preparedExpression.Calculate(parameters, out result, out error));
        }
Beispiel #22
0
 private void Button_Enter(object sender, RoutedEventArgs e)
 {
     try
     {
         PreparedExpression   preparedExpression = ToolsHelper.Parser.Parse(TextBox_In.Text);
         CompiledExpression   compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);
         List <VariableValue> variables          = new List <VariableValue>();
         double res = ToolsHelper.Calculator.Calculate(compiledExpression, variables);
         TextBox_Resul.Text = String.Format("Результат: {0}", res);
     }
     catch (CompilerSyntaxException ex)
     {
         TextBox_Resul.Text = String.Format("Ошибка: {0}", ex.Message);
     }
     catch (MathProcessorException ex)
     {
         TextBox_Resul.Text = String.Format("Ошибка: {0}", ex.Message);
     }
     catch (ArgumentException)
     {
         TextBox_Resul.Text = "Ошибка";
     }
 }
Beispiel #23
0
        /// <summary>
        /// Returns a compiled expression for specified source string.
        /// </summary>
        public CompiledExpression Compile(PreparedExpression preparedExpression)
        {
            if (preparedExpression == null)
            {
                throw new ArgumentNullException("preparedExpression");
            }
            //
            OperationsStack operationsStack = new OperationsStack(operationsRegistry);

            //
            for (int itemIndex = 0; itemIndex < preparedExpression.PreparedExpressionItems.Count; itemIndex++)
            {
                PreparedExpressionItem item = preparedExpression.PreparedExpressionItems[itemIndex];
                // If constant or variable - add to result
                if (item.Kind == PreparedExpressionItemKind.Constant)
                {
                    operationsStack.PushConstant(item.Constant);
                }
                if (item.Kind == PreparedExpressionItemKind.Variable)
                {
                    operationsStack.PushVariable(item.VariableName);
                }
                // If delimiter
                if (item.Kind == PreparedExpressionItemKind.Delimiter)
                {
                    operationsStack.PushDelimiter(item.DelimiterKind);
                }
                // Signature (operator signature / part of signature / function)
                if (item.Kind == PreparedExpressionItemKind.Signature)
                {
                    List <Operation> operations = new List <Operation>(operationsRegistry.GetOperationsUsingSignature(item.Signature));
                    operations.Sort(new Comparison <Operation>(compareOperationsByOperandsCount));
                    //
                    for (int i = 0; i < operations.Count; i++)
                    {
                        Operation operation = operations[i];
                        // Operator
                        if (operation.Kind == OperationKind.Operator)
                        {
                            // Unary operator
                            if (operation.OperandsCount == 1)
                            {
                                // If operator placed at the start of subexpression
                                if ((itemIndex == 0) ||
                                    ((itemIndex > 0) && (preparedExpression.PreparedExpressionItems[itemIndex - 1].Kind == PreparedExpressionItemKind.Delimiter) && (preparedExpression.PreparedExpressionItems[itemIndex - 1].DelimiterKind == DelimiterKind.OpeningBrace) || (preparedExpression.PreparedExpressionItems[itemIndex - 1].DelimiterKind == DelimiterKind.Comma)))
                                {
                                    //
                                    operationsStack.PushUnaryOperator(operation);
                                    break;
                                }
                            }
                            // Binary operator
                            if (operation.OperandsCount == 2)
                            {
                                operationsStack.PushBinaryOperator(operation);
                                break;
                            }
                            // Ternary and more
                            if (operation.OperandsCount > 2)
                            {
                                int partNumber = 0;
                                for (int k = 0; k < operation.Signature.Length; k++)
                                {
                                    if (operation.Signature[k] == item.Signature)
                                    {
                                        partNumber = k + 1;
                                        break;
                                    }
                                }
                                // If it is start part in signature
                                if (partNumber == 1)
                                {
                                    operationsStack.PushComplexOperatorFirstSignature(operation);
                                    break;
                                }
                                //
                                operationsStack.PushComplexOperatorNonFirstSignature(operation, partNumber);
                                break;
                            }
                        }
                        // Function
                        if (operation.Kind == OperationKind.Function)
                        {
                            operationsStack.PushFunction(operation);
                            break;
                        }
                    }
                }
            }
            //
            operationsStack.DoFinalFlush();
            //
            CompiledExpression res = operationsStack.GetResult();

            if (!isCompiledExpressionStackBalanced(res))
            {
                throw new CompilerSyntaxException("Operands disbalance detected.");
            }
            return(res);
        }
        public Function(String expression)
        {
            PreparedExpression preparedExpression = ToolsHelper.Parser.Parse(expression);

            compiledExpression = ToolsHelper.Compiler.Compile(preparedExpression);
        }