public TaylorSeriesCompute(int iterations, Expr symbol, Expr value, Expr function, Expr functionInput)
        {
            //initiliaze
            DerivativeList = new List <TaylorSeriesIteration>();

            //create the series
            var series = Taylor(iterations, symbol, value, function);

            //eval
            var symbols = new Dictionary <string, FloatingPoint>();

            symbols.Add("x", 1);
            try {
                var eval = Evaluate.Evaluate(symbols, functionInput);
                //assign values
                this.Aprox = eval;
            } catch {
                throw new ArgumentException("Invalid function input");
            }

            //assign to results
            this.SeriesExpression = series;
            this.InputFunction    = function;

            //var X = Expr.Symbol("x");
            //var sample = Taylor(6, X, 0, Expr.Cos(X));

            //string res = Infix.Format(sample);
            //Console.WriteLine("taylor series: {0}", res);
        }
        private decimal EvaluateFunctDerivative(decimal value)
        {
            Dictionary <string, FloatingPoint> symbols = new Dictionary <string, FloatingPoint>();

            symbols.Add(SymbolStr, (double)value);
            return((decimal)Evaluate.Evaluate(symbols, FunctDerivative).RealValue);
        }
示例#3
0
        public static Expression ChooseWithDiff(Expression h, int k, int times, int sign)
        {
            if (k < 1)
            {
                return(0);
            }

            var u = Expression.Symbol("u");

            var d = (u.Factorial(k - 1, sign));

            for (var i = 0; i < times; i++)
            {
                d = Calculus.Differentiate(u, d);
            }

            var result = d / k.Factorial();


            var floatingPoint = Evaluate.Evaluate(
                new Dictionary <string, FloatingPoint> {
                {
                    "u", FloatingPoint.NewReal(h.ToReal())
                }
            },
                result);

            var frac = (Expression)floatingPoint.RealValue.ToFraction(); // k.Factorial();


            return(frac);
        }
        static void Multiple_Roots(Expression f, float x0, float tol, int ite)
        {
            var xdict = new Dictionary <string, FloatingPoint> {
                { "x", x0 }
            };

            Expression x   = Expression.Symbol("x");
            Expression df  = Calculus.Differentiate(x, f);
            Expression d2f = Calculus.Differentiate(x, df);

            int   cont     = 0;
            float absError = tol + 1;
            float relError;
            float x1;

            float fx          = (float)Evaluate.Evaluate(xdict, f).RealValue;
            float dfx         = (float)Evaluate.Evaluate(xdict, df).RealValue;
            float d2fx        = (float)Evaluate.Evaluate(xdict, d2f).RealValue;
            float denominator = (float)Math.Pow(dfx, 2) - (fx * d2fx);

            Console.WriteLine("|{0,-4}|{1,-15}|{2,-15}|{3,-15}|{4,-15}|{5,-15}|{6,-15}|", "cont", "x", "fx", "dfx", "d2fx", "AbsError", "RelError");
            Console.WriteLine("|{0,-4}|{1,-15}|{2,-15}|{3,-15}|{4,-15}|{5,-15}|{6,-15}|", cont, x0, fx, dfx, d2fx, "", "");

            while (fx != 0 && absError > tol && denominator != 0 && cont < ite)
            {
                x1         = x0 - ((fx * dfx) / denominator);
                xdict["x"] = x1;

                fx          = (float)Evaluate.Evaluate(xdict, f).RealValue;
                dfx         = (float)Evaluate.Evaluate(xdict, df).RealValue;
                d2fx        = (float)Evaluate.Evaluate(xdict, d2f).RealValue;
                denominator = (float)Math.Pow(dfx, 2) - (fx * d2fx);

                absError = Math.Abs(x1 - x0);
                relError = absError / Math.Abs(x1);
                x0       = x1;
                cont++;
                Console.WriteLine("|{0,-4}|{1,-15}|{2,-15}|{3,-15}|{4,-15}|{5,-15}|{6,-15}|", cont, x0, fx, dfx, d2fx, absError, relError);
            }

            if (fx == 0)
            {
                Console.WriteLine("\n" + x0 + " is a root.");
            }
            else if (absError < tol)
            {
                Console.WriteLine("\n" + x0 + " approximates to the function's root with a tolerance of: " + tol.ToString());
            }
            else if (denominator == 0)
            {
                Console.WriteLine("\n" + x0 + " denominator became 0");
            }
            else
            {
                Console.WriteLine("\n" + "Maximum number of iterations exceeded.");
            }
        }
示例#5
0
        static void Main(string[] args)
        {
            Console.Write("Expression: ");
            var expr   = Console.ReadLine();
            var parsed = Infix.ParseOrThrow(expr);
            var res    = Evaluate.Evaluate(new Dictionary <String, FloatingPoint>(), parsed);

            Console.WriteLine(res);
        }
        public static double Eval(this Expression expr, double x)
        {
            var variables = new Dictionary <string, FloatingPoint>
            {
                { "x", x }
            };

            return(Evaluate.Evaluate(variables, expr).RealValue);
        }
示例#7
0
        private void calculateFuncAi(string sFunction, double x)
        {
            var e      = Infix.ParseOrUndefined(sFunction);
            var result = Evaluate.Evaluate(new Dictionary <string, FloatingPoint> {
                { "x", x }
            }, e);

            _model.funcAi = result.RealValue;
        }
示例#8
0
        public double GetValue(IPoint p)
        {
            Dictionary <string, FloatingPoint> values = new Dictionary <string, FloatingPoint>();

            for (int i = 0; i < dimentions; ++i)
            {
                values.Add("X" + (i + 1).ToString(), p.GetPointOnAxis(i));
            }
            return(Evaluate.Evaluate(values, Infix.ParseOrUndefined(function_string)).RealValue);
        }
        //create the function
        Expr Taylor(int iterations, Expr symbol, Expr value, Expr function)
        {
            this.DerivativeList.Clear();

            //counter for factorial
            int factorial = 1;

            //accumulates the results for each iteration (formula)
            Expr accumulator = Expr.Zero;

            //variable for holding the derivative of function for each iteration
            Expr derivative = function;

            for (int i = 0; i < iterations; i++)
            {
                //use for storing output
                TaylorSeriesIteration OutputItem = new TaylorSeriesIteration();

                //store the current iteration
                OutputItem.Iteration = (i + 1).ToString();

                //subs/replaces symbol with value from funct. Ex. symbol: x, func: x + 1, value: 1 result: 1 + 1
                var subs = Structure.Substitute(symbol, value, derivative);

                //get the derivative of derivative with respect to symbol
                derivative = Calculus.Differentiate(symbol, derivative);

                //output current derivative
                OutputItem.Function = derivative;

                //evaluate derivative, f(0)
                var evalValue = new Dictionary <string, FloatingPoint> {
                    { Infix.Format(symbol), 1 }
                };
                var eval = Evaluate.Evaluate(evalValue, Structure.Substitute(symbol, 0, derivative));
                OutputItem.Evaluation = eval.ToString();

                //create the formula and append to accumulator
                accumulator = accumulator + subs / factorial * Expr.Pow(symbol - value, i);

                //output current formula
                OutputItem.Series = accumulator;

                //current iteration + 1 as factorial (cause 0-based loop)
                factorial *= (i + 1);

                //append to list
                this.DerivativeList.Add(OutputItem);
            }

            //return the formula/func in expanded form
            return(Algebraic.Expand(accumulator));
        }
示例#10
0
        public async Task <SearchResultCollection> SearchAsync(SearchQuery query, CancellationToken ct)
        {
            string latex;
            string infix;
            double?evaluated;

            try
            {
                // simplify
                var expression = Infix.ParseOrThrow(query.QueryString);
                latex = LaTeX.Format(expression);
                infix = Infix.Format(expression);

                // try to calculate
                var symbols = new Dictionary <string, FloatingPoint>();
                try
                {
                    evaluated = Evaluate.Evaluate(symbols, expression).RealValue;
                }
                catch (Exception ex)
                {
                    // expression valid, but can't be calculated
                    return(null);
                }
            }
            catch (Exception ex)
            {
                // expression error
                return(null);
            }

            var results = new SearchResultCollection
            {
                Title           = "Math evaluation",
                Relevance       = evaluated != null ? SearchResultRelevance.ONTOP : SearchResultRelevance.DEFAULT,
                FontAwesomeIcon = "Calculator"
            };

            results.Results = new ObservableCollection <SearchResult>
            {
                new MathSearchResult
                {
                    Title            = infix,
                    LaTeXExpression  = latex,
                    LaTeXEvaluated   = evaluated != null ? "= " + evaluated : "",
                    ParentCollection = results
                }
            };

            return(results);
        }
        public static Func <int, int, double> ParseInput(string input)
        {
            var e = Expr.Symbol("edges");
            var v = Expr.Symbol("vertices");

            return((vertices, edges) =>
            {
                var symbols = new Dictionary <string, FloatingPoint>
                {
                    { "vertices", vertices },
                    { "edges", edges }
                };

                return Evaluate.Evaluate(symbols, Infix.ParseOrUndefined(input)).RealValue;
            });
        }
示例#12
0
        public void FunctionTest_PasreAndEval()
        {
            var symbols = new Dictionary <string, FloatingPoint>
            {
                { "X1", 2d },
                { "X2", 2d },
                { "X3", 2d }
            };
            string    function = "1/(X1*X2*X3)";
            IFunction func     = new MathCore.Function(function, 3);

            //проеряем, что результат вычисления функции и реализации из библиотеки совпадают
            Assert.AreEqual(func.GetValue(new Point(new List <double> {
                2d, 2d, 2d
            })), Evaluate.Evaluate(symbols, Infix.ParseOrUndefined(function)).RealValue);
        }
        public double EvaluateInX(string sFunction, double x)
        {
            if (!isValidFunction(sFunction))
            {
                throw new Exception("Error de sintaxis en la ecuación: " + sFunction);
            }

            var e      = Infix.ParseOrUndefined(sFunction);
            var result = Evaluate.Evaluate(new Dictionary <string, FloatingPoint> {
                { "x", x }
            }, e);

            if (!result.IsReal)
            {
                throw new Exception("El resultado no es un número real");
            }

            return(result.RealValue);
        }
        static void Secant(Expression f, float x0, float x1, float tol, int ite)
        {
            var x0dict = new Dictionary <string, FloatingPoint> {
                { "x", x0 }
            };

            float fx0 = (float)Evaluate.Evaluate(x0dict, f).RealValue;

            if (fx0 == 0)
            {
                Console.WriteLine("\n" + x0 + " is a root.");
            }
            else
            {
                var x1dict = new Dictionary <string, FloatingPoint> {
                    { "x", x1 }
                };
                int   cont = 0;
                float x2;
                float absError = tol + 1;
                float relError;

                float fx1         = (float)Evaluate.Evaluate(x1dict, f).RealValue;
                float denominator = fx1 - fx0;

                Console.WriteLine("|{0,-4}|{1,-15}|{2,-15}|{3,-15}|{4,-15}|{5,-15}|{6,-15}|", "cont", "x0", "x1", "fx0", "fx1", "AbsError", "RelError");
                Console.WriteLine("|{0,-4}|{1,-15}|{2,-15}|{3,-15}|{4,-15}|{5,-15}|{6,-15}|", cont, x0, x1, fx0, fx1, "", "");

                while (fx1 != 0 && absError > tol && denominator != 0 && cont < ite)
                {
                    x0          = (float)x0dict["x"].RealValue;
                    x1          = (float)x1dict["x"].RealValue;
                    x2          = x1 - ((fx1 * (x1 - x0)) / denominator);
                    absError    = Math.Abs(x2 - x1);
                    relError    = absError / Math.Abs(x2);
                    x0          = x1;
                    fx0         = fx1;
                    x1          = x2;
                    x1dict["x"] = x0;
                    x1dict["x"] = x1;
                    fx1         = (float)Evaluate.Evaluate(x1dict, f).RealValue;
                    denominator = fx1 - fx0;
                    cont++;
                    Console.WriteLine("|{0,-4}|{1,-15}|{2,-15}|{3,-15}|{4,-15}|{5,-15}|{6,-15}|", cont, x0, x1, fx0, fx1, absError, relError);
                }

                if (fx1 == 0)
                {
                    Console.WriteLine("\n" + x0 + " is a root.");
                }
                else if (absError < tol)
                {
                    Console.WriteLine("\n" + x0 + " approximates to the function's root with a tolerance of: " + tol.ToString());
                }
                else if (denominator == 0)
                {
                    Console.WriteLine("\n" + x0 + " is possibly a multiple root.");
                }
                else
                {
                    Console.WriteLine("\n" + "Maximum number of iterations exceeded.");
                }
            }
        }
示例#15
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public double Eval()
 {
     return(Evaluate.Evaluate(symbolValues, infix).RealValue);
 }
示例#16
0
        public string GetSqrt(string espression)
        {
            string result      = String.Empty;
            string AddToResult = "";

            espression = espression.Replace('.', ',');
            double num;

            if (Double.TryParse(espression, out num))
            {
                if (num < 0 && num % 1 != 0)
                {
                    espression  = espression.Substring(1);
                    AddToResult = "*i";
                }
            }
            espression = espression.Replace(',', '.');


            var expression = Infix.ParseOrUndefined("sqrt(" + espression + ")");


            if (expression == Expression.Undefined)
            {
                throw new SqrtException("Unable to parse expression");
            }

            try
            {
                var sub_result = Evaluate.Evaluate(null, expression);

                if (sub_result.IsReal)
                {
                    if (sub_result.RealValue != 0)
                    {
                        result = "+/- " + sub_result.RealValue.ToString();
                    }
                    else
                    {
                        result = "0";
                    }
                }
                else if (sub_result.IsComplex)
                {
                    result = sub_result.ComplexValue.Real.ToString() + " + i*" + sub_result.ComplexValue.Imaginary.ToString();
                }
                else
                {
                    result = sub_result.ToString();
                }
            }
            catch (NullReferenceException ex)
            {
                result = Infix.Format(Calculus.Taylor(5, Infix.ParseOrThrow(espression), Infix.ParseOrThrow("1"), expression)) + " + ...";
            }
            int i = 0;

            while (i < result.Length)
            {
                if (result[i] == ',')
                {
                    int j = i + 1;
                    for (; j - i < _accuracy && j < result.Length && Char.IsNumber(result[j]); j++)
                    {
                    }
                    i = j + 1;
                    for (; j < result.Length && Char.IsNumber(result[j]); j++)
                    {
                    }
                    if (_accuracy == 0)
                    {
                        i = i - 2;
                    }
                    result = result.Remove(i, j - i);
                }
                else
                {
                    i++;
                }
            }
            return(result + AddToResult);
        }
示例#17
0
        /// <summary>
        /// Create trajectory from given parametrization
        /// </summary>
        private void CreateTrajectory()
        {
            // Try to parse parametrizations' strings
            try
            {
                xExpression = Infix.ParseOrThrow(XParametrizationTextBox.Text);
                yExpression = Infix.ParseOrThrow(YParametrizationTextBox.Text);
            }
            catch (Exception exception)
            {
                TrajectoryLoaded = false;
                MessageBox.Show("Wrong format of parametrization.\n" + exception.Message);
                return;
            }

            // Try to parse parameters
            try
            {
                minParameterValue = double.Parse(MinParameterValueTextBox.Text);
                maxParameterValue = double.Parse(MaxParameterValueTextBox.Text);
                pointsCount       = double.Parse(PointsCountTextBox.Text);
                if (minParameterValue >= maxParameterValue || pointsCount < 2)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                TrajectoryLoaded = false;
                MessageBox.Show("Parameters are invalid.");
                return;
            }

            TrajectoryPoints = new List <Point3D>();

            var flag = true;

            // Try to calculate curve's trajectory
            try
            {
                var parameterStep = (maxParameterValue - minParameterValue) / (pointsCount - 1);
                for (double t = minParameterValue; t < maxParameterValue + parameterStep / 2; t += parameterStep)
                {
                    symbols["t"] = t;
                    double xResult = Evaluate.Evaluate(symbols, xExpression).RealValue;
                    double yResult = Evaluate.Evaluate(symbols, yExpression).RealValue;
                    TrajectoryPoints.Add(new Point3D(xResult, yResult, 0.0));
                    if (flag)
                    {
                        flag = false;
                    }
                }
            }
            catch (Exception exception)
            {
                TrajectoryLoaded = false;
                TrajectoryPoints.Clear();
                if (exception.HResult == HResultWrongParam)
                {
                    MessageBox.Show("Given parametrization is not based on [t] variable.\n");
                }
                else if (exception.HResult == HResultCannotCalculate)
                {
                    MessageBox.Show("Cannot calculate curve for given set.\n");
                }
                else
                {
                    MessageBox.Show("Cannot calculate curve for given set.\n" + exception.Message);
                }
                return;
            }
            TrajectoryLoaded = true;
        }
示例#18
0
        /// <summary>
        /// 去读配置项重新计算结果,更新数据
        /// </summary>
        public static void ReCalculation(string projectId)
        {
            var list = DAL.CommonDAL.GetProjectItemList(projectId);

            var tongjiList = new List <Model.Tongji>();

            #region 加载配置
            Model.SysConfig config = ReadConfig();
            if (config == null || string.IsNullOrEmpty(config.HanLiang))
            {
                return;
            }
            #endregion

            #region 计算含量
            Action <Model.DrugProjectItem> countHL = (Model.DrugProjectItem s) =>
            {
                try
                {
                    var dic = new Dictionary <string, FloatingPoint>()
                    {
                        { "供试峰面积", float.Parse(s.PJSFMJ) },
                        { "供试称样量", float.Parse(s.GSCYL) },
                        { "稀释倍数", float.Parse(s.XSBS) },
                        { "对照浓度", float.Parse(s.DZLD) },
                        { "对照峰面积", float.Parse(s.DZFMJ) }
                    };
                    FloatingPoint value = Evaluate.Evaluate(dic, Infix.ParseOrUndefined(config.HanLiang));
                    s.HL = Math.Round(value.RealValue, config.HanLiangPoint, MidpointRounding.AwayFromZero).ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            };
            #endregion

            #region 计算平均含量和方差

            list.ForEach(s => countHL(s));

            var yplist = list.Where(s => s.type.Trim() == Model.DrugType.饮片.ToString());
            var tjlist = list.Where(s => s.type.Trim() == Model.DrugType.汤剂.ToString());

            Action <string, double, bool> addTongji = (string key, double PJHL, bool isYp) =>
            {
                if (isYp)
                {
                    if (tongjiList.Any(s => s.GroupName == key))
                    {
                        tongjiList.Where(s => s.GroupName == key).FirstOrDefault().YPHL = PJHL;
                    }
                    else
                    {
                        tongjiList.Add(new Model.Tongji()
                        {
                            GroupName = key, YPHL = PJHL
                        });
                    }
                }
                else
                {
                    if (tongjiList.Any(s => s.GroupName == key))
                    {
                        tongjiList.Where(s => s.GroupName == key).FirstOrDefault().TJHL = PJHL;
                    }
                    else
                    {
                        tongjiList.Add(new Model.Tongji()
                        {
                            GroupName = key, TJHL = PJHL
                        });
                    }
                }
            };

            Action <List <Model.DrugProjectItem>, bool> countPJHL = (List <Model.DrugProjectItem> models, bool fc) =>
            {
                foreach (var item in models.GroupBy(s => s.CodeNum1))
                {
                    double          PJHL   = 0;
                    int             lastId = 0;
                    List <FcEntity> fclist = new List <Win.FcEntity>();
                    int             index  = 0;
                    foreach (var sitem in item)
                    {
                        PJHL  += Convert.ToDouble(sitem.HL);
                        lastId = sitem.ID;
                        if (index > 1)
                        {
                            index = 0;
                        }
                        fclist.Add(new Win.FcEntity()
                        {
                            HL = Convert.ToDouble(sitem.HL), ID = sitem.ID
                        });
                    }
                    if (lastId != 0 && item.Count() > 1)
                    {
                        PJHL = Math.Round(PJHL / item.Count(), config.PingJunHLPoint, MidpointRounding.AwayFromZero);
                        list.Where(s => s.ID == lastId).FirstOrDefault().PJHL = PJHL.ToString();
                        addTongji(item.Key, PJHL, fc);
                        if (fc)
                        {
                            if (fclist.Count >= 2)
                            {
                                double fac = 0;
                                fclist = fclist.OrderBy(s => s.ID).ToList();
                                for (int i = 1; i < fclist.Count; i++)
                                {
                                    fac = fclist[i - 1].HL - fclist[i].HL;
                                }
                                list.Where(s => s.ID == lastId).FirstOrDefault().FC = Math.Round(fac, config.FangChaPoint, MidpointRounding.AwayFromZero).ToString();
                            }
                        }
                    }
                }
            };

            countPJHL(yplist.Where(s => s.IsFuCe == "False").ToList(), true);
            countPJHL(yplist.Where(s => s.IsFuCe != "False").ToList(), true);

            countPJHL(tjlist.Where(s => s.IsFuCe == "False").ToList(), false);
            countPJHL(tjlist.Where(s => s.IsFuCe != "False").ToList(), false);

            #endregion

            #region 统计数据
            foreach (var item in tongjiList)
            {
                item.ZYLv = Math.Round((item.TJHL / item.YPHL) * 100, 2, MidpointRounding.AwayFromZero);
            }
            DAL.CommonDAL.AddProjectTongji(tongjiList, projectId);
            #endregion

            #region  计算完毕更新数据库

            foreach (var item in list)
            {
                DAL.CommonDAL.UpdateProjectItem(item);
            }
            #endregion
        }