Exemplo n.º 1
0
 public GameProcessViewModel()
 {
     _expression    = new MathExpression(1, 10, true, false, false, false);
     _question      = new Question(_expression);
     _listOfAnswers = new List <int>(_question.getListOfAnswers());
     getQuestion();
 }
Exemplo n.º 2
0
        private double[][] GenerateAMatrix(int N, MathExpression tFunc, MathExpression bFunc, MathExpression sigmaFunc)
        {
            double h = 1.0 / N;

            double[][] res = new double[N][];
            for (int i = 0; i < N; i++)
            {
                res[i] = new double[N];
                for (int j = 0; j < N; j++)
                {
                    if (i != N - 1)
                    {
                        if (i == j)
                        {
                            res[i][j] = (1.0 / h) * (tFunc.Calculate(h * (i + 1) - (h / 2.0)) + tFunc.Calculate(h * (i + 1) + (h / 2.0))) +
                                        (h / 3.0) *
                                        (sigmaFunc.Calculate(h * (i + 1) - (h / 2.0)) + sigmaFunc.Calculate(h * (i + 1) + (h / 2.0))) +
                                        (1.0 / 2.0) * (bFunc.Calculate(h * (i + 1) - (h / 2.0)) - bFunc.Calculate(h * (i + 1) + (h / 2.0)));
                        }
                        else if (j == i + 1)
                        {
                            res[i][j] = -(1.0 / h) * tFunc.Calculate(h * (i + 1) + (h / 2.0)) +
                                        (1.0 / 2.0) * bFunc.Calculate(h * (i + 1) + (h / 2.0)) +
                                        (h / 6.0) * sigmaFunc.Calculate(h * (i + 1) + (h / 2.0));
                        }
                        else if (j == i - 1)
                        {
                            res[i][j] = -(1.0 / h) * tFunc.Calculate(h * (i + 1) - (h / 2.0)) -
                                        (1.0 / 2.0) * bFunc.Calculate(h * (i + 1) - (h / 2.0)) +
                                        (h / 6.0) * sigmaFunc.Calculate(h * (i + 1) - (h / 2.0));
                        }
                        else
                        {
                            res[i][j] = 0;
                        }
                    }
                    else
                    {
                        if (j < N - 2)
                        {
                            res[i][j] = 0;
                        }
                        else if (j == N - 2)
                        {
                            res[i][j] = -(1.0 / h) * tFunc.Calculate(h * (i + 1) - (h / 2.0)) -
                                        (1.0 / 2.0) * bFunc.Calculate(h * (i + 1) - (h / 2.0)) +
                                        (h / 6.0) * sigmaFunc.Calculate(h * (i + 1) - (h / 2.0));
                        }
                        else if (j == N - 1)
                        {
                            res[i][j] = (1.0 / h) * tFunc.Calculate(h * (i + 1) - (h / 2.0)) +
                                        (1.0 / 2.0) * bFunc.Calculate(h * (i + 1) - (h / 2.0)) +
                                        (h / 3.0) * sigmaFunc.Calculate(h * (i + 1) - (h / 2.0));
                        }
                    }
                }
            }

            return(res);
        }
Exemplo n.º 3
0
        public static double CalculateWithAccuracy(double a, double b, MathExpression function, double epsilon, params Var[] variables)
        {
            List <double> Xk = new List <double>()
            {
                -0.8611363, -0.3399810, 0.3399810, 0.8611363
            };
            List <double> Ck = new List <double>()
            {
                0.3478548, 0.6521452, 0.6521452, 0.3478548
            };

            double result;
            int    n = 1;

            double newResult = Calculate(a, b, n, function, variables);

            do
            {
                n        *= 2;
                result    = newResult;
                newResult = Calculate(a, b, n, function, variables);
            }while (System.Math.Abs(newResult - result) > epsilon);

            return(newResult);
        }
Exemplo n.º 4
0
        public static double Calculate(double a, double b, int amountOfPartitions, MathExpression function, params Var[] variables)
        {
            List <double> Xk = new List <double>()
            {
                -0.8611363, -0.3399810, 0.3399810, 0.8611363
            };
            List <double> Ck = new List <double>()
            {
                0.3478548, 0.6521452, 0.6521452, 0.3478548
            };

            double result = 0;

            double step = (b - a) / amountOfPartitions;

            for (int i = 0; i < amountOfPartitions; i++)
            {
                double a_new = a + step * i;
                double b_new = a + step * (i + 1);

                double sum = 0;
                for (int j = 0; j < Xk.Count; j++)
                {
                    variables[0].Value = (a_new + b_new) / 2.0 + (b_new - a_new) / 2.0 * Xk[j];
                    sum += Ck[j] * function.Calculate(variables);
                }

                result += sum * (b_new - a_new) / 2.0;
            }

            return(result);
        }
Exemplo n.º 5
0
        public async Task TestMathExpression_ApiUriShouldWork()
        {
            string controller     = "api/calculator/evaluateexpression";
            var    mathExpression = new MathExpression()
            {
                Expression = "1+2"
            };

            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(baseUri);
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await httpClient.PostAsJsonAsync(controller, mathExpression);

                Assert.IsNotNull(response);
                Assert.IsTrue(response.IsSuccessStatusCode);

                var x = await response.Content.ReadAsAsync <MathExpression>();

                Assert.IsNotNull(x);
                Assert.IsNotNull(x.Key);
                Assert.AreEqual(3, x.Key);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Optimizes the provided expression using an <see cref="OptimizationContext{TSettings}"/>
        /// created with <see cref="OptimizationContext.CreateDefault(DefaultOptimizationSettings?, IEnumerable{IOptimizationPass{DefaultOptimizationSettings}})"/>
        /// </summary>
        /// <param name="expr">the expression to optimize</param>
        /// <returns>the optimized expression</returns>
        public override MathExpression Optimize(MathExpression expr)
        {
            var ctx = OptimizationContext.CreateDefault(OptimizerSettings, OptimizerPasses);

            ctx.SetParentDataContext(SharedDataStore);
            return(ctx.Optimize(expr));
        }
 public void SolveTest()
 {
     Assert.AreEqual(MathExpression.Solve("((2+2)*2+2*(2+2*(2+2))+2*2)+2+2*2*2+2"), 44);
     Assert.AreEqual(MathExpression.Solve("2+2*(2+2*2+(2+2*(2+2)))"), 34);
     Assert.AreEqual(MathExpression.Solve("(((25+227)/2)+134)*2+((48+2)*(2+2))"), 720);
     Assert.AreEqual(MathExpression.Solve("4*2+3-78+16*(21*3-7)+88/4"), 851);
 }
        public void Define(string variable, MathExpression expression)
        {
            try
            {
                _lock.EnterWriteLock();

                // Make sure the variable isn't refering to itself.
                if (_variableFinder.HasVariableDefined(expression, this, variable))
                {
                    string message = string.Format("Variable '{0}' is refering to itself recursively.", variable);
                    throw new MathExpressionException(message);
                }

                if (_lookup.ContainsKey(variable))
                {
                    _lookup[variable] = expression;
                }
                else
                {
                    _lookup.Add(variable, expression);
                }
            }
            finally
            {
                _lock.ExitWriteLock();
            }
        }
Exemplo n.º 9
0
        public void CompileVariable(MathExpression expr, Type expectType, string paramName, object parameter, object result)
        {
            var context = CompilationContext.CreateWith(new DefaultLinqExpressionCompilerSettings
            {
                ExpectReturn = expectType,
            }, new DefaultLinqExpressionCompiler <DefaultLinqExpressionCompilerSettings>());

            var objParam = Expression.Parameter(typeof(object));
            var var      = Expression.Variable(expectType);

            context.Settings.ParameterMap.Add(new VariableExpression(paramName), var);

            var fn = Expression.Lambda <Func <object, object> >(
                Expression.Block(
                    new[] { var },
                    Expression.Assign(var, Expression.Convert(objParam, expectType)),
                    Expression.Convert(
                        context.Compile(expr),
                        typeof(object)
                        )
                    ),
                objParam
                ).Compile();

            Assert.Equal(fn(parameter), result);
        }
        public void CriacaoMathExpressionTest(object[] actual, double expected)
        {
            var aux = new MathExpression(actual[0].ToString());
            var x   = Convert.ToDouble(actual[1]);

            Assert.AreEqual(expected, aux.F(x));
        }
Exemplo n.º 11
0
        public static MathExpression GetExpression(string entry, Tokenizer tokenizer, Data data)
        {
            var tokens = tokenizer.Tokenize(entry);
            List <Expression> exprs = new List <Expression>();

            foreach (var token in tokens)
            {
                if (Tokenizer.isValue(token.type))
                {
                    if (token.type == TokenType.ID)
                    {
                        exprs.Add(new Reference(token.value, data));
                    }
                    else
                    {
                        exprs.Add(new Constant(token.value));
                    }
                }
                else if (Tokenizer.isOperator(token.type))
                {
                    exprs.Add(new Operator(token.type));
                }
            }
            MathExpression math = new MathExpression(exprs);

            return(math);
        }
Exemplo n.º 12
0
        // Recursivlly go down the tree
        // IMPORTANT dont forget to return :)
        // otherway Your expression will unfold which will result with unpredicted behaviour
        private double ResolveTree(double result, MathExpression expressionTree, double extras)
        {
            if (expressionTree == null)
            {
                return(result + extras);
            }

            if (HasPriority(expressionTree.Operation))
            {
                extras = MakeOperation(extras, expressionTree.Value, expressionTree.Operation);
                return(ResolveTree(result, expressionTree.Next, extras));
            }

            // if next operation has priority over current one
            // assing current value to extras and move to next expression
            if (expressionTree.Next != null &&
                HasPriority(expressionTree.Next.Operation))
            {
                extras = expressionTree.Value;
                return(ResolveTree(result, expressionTree.Next, extras));
            }

            result = MakeOperation(result, expressionTree.Value, expressionTree.Operation) + extras;
            extras = 0.0;

            return(ResolveTree(result, expressionTree.Next, extras));
        }
Exemplo n.º 13
0
        public void Test_Printing_Instructions_For_Long_Expressions()
        {
            var expression   = new MathExpression("7/2+14*9-5-15*500");
            var instructions = new StringBuilder();

            instructions.AppendLine("PUSH 7");
            instructions.AppendLine("PUSH 2");
            instructions.AppendLine("DIVIDE");
            instructions.AppendLine("PUSH 14");
            instructions.AppendLine("ADD");
            instructions.AppendLine("PUSH 9");
            instructions.AppendLine("MULTIPLY");
            instructions.AppendLine("PUSH 5");
            instructions.AppendLine("SUBTRACT");
            instructions.AppendLine("PUSH 15");
            instructions.AppendLine("SUBTRACT");
            instructions.AppendLine("PUSH 500");
            instructions.AppendLine("MULTIPLY");
            instructions.AppendLine("PRINT");

            StringAssert.AreEqualIgnoringCase(
                expression.createProgramInstructions().ToString(),
                instructions.ToString()
                );
        }
Exemplo n.º 14
0
 private static bool CanAddArithmaticOperator(MathExpression expression)
 {
     return(!(expression.Expression.EndsWith("+") ||
              expression.Expression.EndsWith("-") ||
              expression.Expression.EndsWith("/") ||
              expression.Expression.EndsWith("*")));
 }
Exemplo n.º 15
0
        public double NewtonRaphson()
        {
            if (DerivadaFuncao == null)
            {
                throw new Exception("Função derivada necessária");
            }

            if (X == null)
            {
                throw new Exception("Valor de X necessário");
            }

            var    funcaoLinha = new MathExpression(DerivadaFuncao);
            var    x           = X;
            double fx;

            var validador = 0;

            do
            {
                x -= _math.F(x) / funcaoLinha.F(x);

                fx = _math.F(x);

                validador++;
                if (validador > short.MaxValue * 1000)
                {
                    throw new Exception("Não conseguimos encontrar o valor");
                }
            } while (Math.Abs(fx) >= Precisao);

            return(x);
        }
Exemplo n.º 16
0
        public void Test_Expression_With_Empty_Operations()
        {
            var expression = new MathExpression("5");

            Assert.AreEqual(expression.FirstValue, 5);
            Assert.AreEqual(expression.Operations.Count, 0);
        }
Exemplo n.º 17
0
        private static string AppendOrReplaceArithmaticOperator(MathExpression expression)
        {
            return

                (CanAddArithmaticOperator(expression) ?
                 string.Format("{0}{1}", expression.Expression, expression.Key) : ReplaceOldOperatorWithNew(expression));
        }
Exemplo n.º 18
0
        public void BinaryCombinerLiteralCombinerPasses(MathExpression input, MathExpression expect)
        {
            var context = OptimizationContext.CreateWith(new DefaultOptimizationSettings(), new BinaryExpressionCombinerPass(), new LiteralCombinerPass());

            var actual = context.Optimize(input);

            Assert.Equal(expect, actual);
        }
Exemplo n.º 19
0
        public void ExponentConstantReductionPass(MathExpression input, MathExpression expect)
        {
            var context = OptimizationContext.CreateWith(null, new BuiltinExponentConstantReductionPass());

            var actual = context.Optimize(input);

            Assert.Equal(expect, actual);
        }
Exemplo n.º 20
0
        public void LiteralCombinerPass(MathExpression input, MathExpression expect)
        {
            var context = OptimizationContext.CreateWith(null, new LiteralCombinerPass());

            var actual = context.Optimize(input);

            Assert.Equal(expect, actual);
        }
Exemplo n.º 21
0
 public OneDimensionDeriveItem(int initialValue, double stepValue, int valueAmplitude, string variableName, MathExpression expression)
 {
     InitialValue = initialValue;
     StepValue    = stepValue;
     Expression   = expression;
     elementCount = valueAmplitude * 2;
     VariableName = variableName;
 }
Exemplo n.º 22
0
 public InputData(string mu, string beta, string sigma, string f, double alpha, double eta)
 {
     _mu    = new MathExpression(mu);
     _beta  = new MathExpression(beta);
     _sigma = new MathExpression(sigma);
     _f     = new MathExpression(f);
     Alpha  = alpha;
     Eta    = eta;
 }
Exemplo n.º 23
0
        public void Test_Expression_With_One_Operation()
        {
            var expression = new MathExpression("10-3");

            Assert.AreEqual(expression.FirstValue, 10);
            var operation = new MathOperation(Operator.Subtract, 3);

            Assert.AreEqual(expression.Operations.FirstOrDefault(), operation);
        }
Exemplo n.º 24
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            MathExpression mathExpression = await db.MathExpressions.FindAsync(id);

            db.MathExpressions.Remove(mathExpression);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
        public void TestCSharpMathSolverCreation()
        {
            IExpressionProvider <MathExpression> provider = new DefaultExpressionTreeProvider(new DoubleValueProvider());
            string         expression       = "1+2/3+5";
            MathExpression targetExpression = BuildTree();

            MathExpression mathExpression = provider.GetExpressions(expression);

            Assert.AreEqual(targetExpression, mathExpression);
        }
Exemplo n.º 26
0
        public double Solve(string expression)
        {
            MathExpression expressionTree = expressionTreeProvider.GetExpressions(expression);

            //skip root and assign its value to extras
            double result = 0.0;

            result = ResolveTree(result, expressionTree.Next, expressionTree.Value);

            return(result);
        }
Exemplo n.º 27
0
        public ZeroFuncao(ZeroFuncaoDto data)
        {
            Funcao         = data.Funcao;
            DerivadaFuncao = data.DerivadaFuncao;
            X  = data.X;
            X2 = data.X2;

            _math    = new MathExpression(Funcao);
            Precisao = data.Precisao != 0 ? data.Precisao : 0.001;
            Ponto    = data.Ponto;
        }
Exemplo n.º 28
0
        private void OnEqualPressCommandExecute(object p)
        {
            if (CurrentExpression.Content != "")
            {
                CurrentExpression.CalculateResult();
                ExpressionHistory.Add(CurrentExpression);
                OnPropertyChanged("CurrentExpression");

                CurrentExpression = new MathExpression();
            }
        }
Exemplo n.º 29
0
        public MainWindowViewModel()
        {
            ButtonPressCommand = new RelayCommand(OnButtonPressCommandExecute, CanButtonPressCommandExecute);
            EqualPressCommand  = new RelayCommand(OnEqualPressCommandExecute, CanEqualPressCommandExecute);
            ClearPressCommand  = new RelayCommand(OnClearPressCommandExecute, CanClearPressCommandExecute);
            DeletePressCommand = new RelayCommand(OnDeletePressCommandExecute, CanDeletePressCommandExecute);
            DotPressCommand    = new RelayCommand(OnDotPressCommandExecute, CanDotPressCommandExecute);

            ExpressionHistory = new ObservableCollection <MathExpression>();
            CurrentExpression = new MathExpression();
        }
Exemplo n.º 30
0
        public List <double> Generate(double[] mesh)
        {
            MathExpression fFunc   = new MathExpression(_presizeFunction);
            List <double>  results = new List <double>();

            for (int i = 0; i < mesh.Length; i++)
            {
                results.Add(fFunc.Calculate(mesh[i]));
            }
            return(results);
        }
 public MathExpression EvaluateExpression(MathExpression mathExpression)
 {
     try
     {
         return(MathHelper.EvaluateExpression(mathExpression));
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
Exemplo n.º 32
0
 protected UnaryExpression(MathExpression expression)
 {
     _expression = expression;
 }
        /// <summary>
        ///     Returns instance of InterpolativeMathFunction with automatically generated derivations.
        /// </summary>
        /// <param name="expression">Interpreted math function of two real variables i.e. "x^2 + y^2".</param>
        /// <returns>
        ///     Instance of class if mathExpression is in correct format, othervise
        ///     returns null;
        /// </returns>
        public static InterpolativeMathFunction FromExpression(MathExpression expression)
        {
            // TODO: osetrit vynimky pre neplatne vstupy
            var f = expression.Interpret();
            var dx = expression.InterpretMathDifferentiation
                (expression.Variables[0]);
            var dy = expression.InterpretMathDifferentiation
                (expression.Variables[1]);
            var dxy = expression.InterpretMathDifferentiation
                (expression.Variables[0], expression.Variables[1]);

            return new InterpolativeMathFunction(f, dx, dy, dxy);
        }
Exemplo n.º 34
0
 protected BinaryExpression(MathExpression left, MathExpression right)
 {
     _left = left;
     _right = right;
 }