Exemplo n.º 1
0
        /// <summary>
        /// Distribute products across sums, using partial fractions if necessary.
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static Expression Expand(this Expression f, Expression x)
        {
            if (f is Product)
            {
                return(ExpandMultiply(f, x));
            }
            else if (f is Sum sum)
            {
                return(Sum.New(sum.Terms.Select(i => i.Expand(x))));
            }
            else if (f is Power power)
            {
                return(ExpandPower(power, x));
            }
            else if (f is Binary binary)
            {
                return(Binary.New(binary.Operator, binary.Left.Expand(x), binary.Right.Expand(x)));
            }
            else if (f is Unary unary)
            {
                return(Unary.New(unary.Operator, unary.Operand.Expand()));
            }

            return(f);
        }
Exemplo n.º 2
0
        protected Expression ProductRule(Expression L, IEnumerable <Expression> R)
        {
            if (R.Empty())
            {
                return(Visit(L));
            }

            bool Lx = L.DependsOn(x);
            bool Rx = R.DependsOn(x);

            if (Lx && Rx)
            {
                // Product rule.
                return(Sum.New(
                           Product.New(new Expression[] { Visit(L) }.Concat(R)),
                           Product.New(L, ProductRule(R.First(), R.Skip(1)))).Evaluate());
            }
            else if (!Lx)
            {
                // L is constant w.r.t. x.
                return(Product.New(L, ProductRule(R.First(), R.Skip(1))).Evaluate());
            }
            else
            {
                // R is constant w.r.t. x.
                return(Product.New(R.Append(Visit(L))).Evaluate());
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Distribute products across sums, using partial fractions if necessary.
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static Expression Expand(this Expression f, Expression x)
        {
            if (f is Product)
            {
                return(ExpandMultiply(f, x));
            }
            else if (f is Sum)
            {
                return(Sum.New(((Sum)f).Terms.Select(i => i.Expand(x))));
            }
            else if (f is Power)
            {
                return(ExpandPower((Power)f, x));
            }
            else if (f is Binary)
            {
                return(Binary.New(((Binary)f).Operator, ((Binary)f).Left.Expand(), ((Binary)f).Right.Expand()));
            }
            else if (f is Unary)
            {
                return(Unary.New(((Unary)f).Operator, ((Unary)f).Operand.Expand()));
            }

            return(f);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Distribute products across sums.
        /// </summary>
        /// <param name="f"></param>
        /// <param name="x"></param>
        /// <returns></returns>
        public static Expression Factor(this Expression f, Expression x)
        {
            // If f is a product, just factor its terms.
            if (f is Product)
            {
                return(Product.New(((Product)f).Terms.Select(i => i.Factor(x))));
            }

            // If if is l^r, factor l and distribute r.
            if (f is Power)
            {
                Expression l = ((Power)f).Left.Factor(x);
                Expression r = ((Power)f).Right;
                return(Product.New(Product.TermsOf(l).Select(i => Power.New(i, r))));
            }

            // If f is a polynomial of x, use polynomial factoring methods.
            if (f is Polynomial && (((Polynomial)f).Variable.Equals(x) || ReferenceEquals(x, null)))
            {
                return(((Polynomial)f).Factor());
            }

            // Try interpreting f as a polynomial of x.
            if (!ReferenceEquals(x, null))
            {
                // If f is a polynomial of x, factor it.
                try
                {
                    return(Polynomial.New(f, x).Factor());
                }
                catch (Exception) { }
            }

            // Just factor out common sub-expressions.
            if (f is Sum)
            {
                Sum s = (Sum)f;

                IEnumerable <Expression> terms = s.Terms.Select(i => i.Factor()).Buffer();

                // All of the distinct factors.
                IEnumerable <Expression> factors = terms.SelectMany(i => FactorsOf(i).Except(1, -1)).Distinct();
                // Choose the most common factor to use.
                Expression factor = factors.ArgMax(i => terms.Count(j => FactorsOf(j).Contains(i)));
                // Find the terms that contain the factor.
                IEnumerable <Expression> contains = terms.Where(i => FactorsOf(i).Contains(factor)).Buffer();
                // If more than one term contains the factor, pull it out and factor the resulting expression (again).
                if (contains.Count() > 1)
                {
                    return(Sum.New(
                               Product.New(factor, Sum.New(contains.Select(i => Binary.Divide(i, factor))).Evaluate()),
                               Sum.New(terms.Except(contains, Expression.RefComparer))).Factor(null));
                }
            }

            return(f);
        }
Exemplo n.º 5
0
 protected override object VisitSum(Sum A)
 {
     foreach (Expression i in A.Terms)
     {
         equal.Push(equal.Peek() - i);
         Visit(Sum.New(A.Terms.ExceptUnique(i)));
         equal.Pop();
     }
     return(null);
 }
Exemplo n.º 6
0
        protected override Expression VisitSum(Sum A)
        {
            IEnumerable <Expression> terms = VisitList(A.Terms);

            if (ReferenceEquals(terms, null))
            {
                return(null);
            }
            return(ReferenceEquals(terms, A.Terms) ? A : Sum.New(terms));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Distribute products across sums.
        /// </summary>
        /// <param name="f"></param>
        /// <param name="x"></param>
        /// <returns></returns>
        public static Expression Factor(this Expression f, Expression x)
        {
            // If f is a product, just factor its terms.
            if (f is Product product)
            {
                return(Product.New(product.Terms.Select(i => i.Factor(x))));
            }

            // If if is l^r, factor l and distribute r.
            if (f is Power power)
            {
                Expression l = power.Left.Factor(x);
                Expression r = power.Right;
                return(Product.New(Product.TermsOf(l).Select(i => Power.New(i, r))));
            }

            // If f is a polynomial of x, use polynomial factoring methods.
            if (f is Polynomial p && (p.Variable.Equals(x) || (x is null)))
            {
                return(p.Factor());
            }

            // Try interpreting f as a polynomial of x.
            if (!(x is null))
            {
                // If f is a polynomial of x, factor it.
                try
                {
                    return(Polynomial.New(f, x).Factor());
                }
                catch (Exception) { }
            }

            // Just factor out common sub-expressions.
            if (f is Sum s)
            {
                // Make a list of each terms' products.
                List <List <Expression> > terms = s.Terms.Select(i => FactorsOf(i).ToList()).ToList();

                // All of the distinct factors.
                IEnumerable <Expression> factors = terms.SelectMany(i => i.Except(1, -1)).Distinct();
                // Choose the most common factor to factor.
                Expression factor = factors.ArgMax(i => terms.Count(j => j.Contains(i)));
                // Find the terms that contain the factor.
                List <List <Expression> > contains = terms.Where(i => i.Contains(factor)).ToList();
                // If more than one term contains the factor, pull it out and factor the resulting expressions (again).
                if (contains.Count() > 1)
                {
                    Expression factored     = Sum.New(contains.Select(i => Product.New(i.Except(factor))));
                    Expression not_factored = Sum.New(terms.Except(contains).Select(i => Product.New(i)));
                    return(Sum.New(Product.New(factor, factored), not_factored).Factor(null));
                }
            }
            return(f);
        }
Exemplo n.º 8
0
        // Expand N(x)/D(x) using partial fractions.
        private static Expression ExpandPartialFractions(Expression N, Expression D, Expression x)
        {
            List <Expression> terms    = new List <Expression>();
            List <Variable>   unknowns = new List <Variable>();
            List <Expression> basis    = new List <Expression>();

            foreach (Expression i in Product.TermsOf(D))
            {
                // Get the multiplicity of this basis term.
                Expression e = i;
                int        n = Power.IntegralExponentOf(e);
                if (n != 1)
                {
                    e = ((Power)i).Left;
                }

                // Convert to a polynomial.
                Polynomial Pi = Polynomial.New(e, x);

                // Add new terms for each multiplicity n.
                for (int j = 1; j <= n; ++j)
                {
                    // Expression for the unknown numerator of this term.
                    Expression unknown = 0;
                    for (int k = 0; k < Pi.Degree; ++k)
                    {
                        Variable Ai = Variable.New("_A" + unknowns.Count.ToString());
                        unknown += Ai * (x ^ k);
                        unknowns.Add(Ai);
                    }

                    terms.Add(Product.New(unknown, Power.New(e, -j)));
                }
                basis.Add(i);
            }

            // Equate the original expression with the decomposed expressions.
            D = Sum.New(terms.Select(j => (Expression)(D * j))).Expand();
            Polynomial l = Polynomial.New(N, x);
            Polynomial r = Polynomial.New(D, x);

            // Equate terms of equal degree and solve for the unknowns.
            int          degree = Math.Max(l.Degree, r.Degree);
            List <Equal> eqs    = new List <Equal>(degree + 1);

            for (int i = 0; i <= degree; ++i)
            {
                eqs.Add(Equal.New(l[i], r[i]));
            }
            List <Arrow> A = eqs.Solve(unknowns);

            // Substitute the now knowns.
            return(Sum.New(terms.Select(i => i.Evaluate(A))));
        }
Exemplo n.º 9
0
 public static Expression operator /(Polynomial N, Polynomial D)
 {
     if (Equals(N.Variable, D.Variable))
     {
         Polynomial R;
         Polynomial Q = Divide(N, D, out R);
         return(Sum.New(Q, Binary.Divide(R, D)));
     }
     else
     {
         return((Expression)N / (Expression)D);
     }
 }
Exemplo n.º 10
0
        protected override Expression VisitProduct(Product M)
        {
            List <Expression> independent = new List <Expression>();
            List <Expression> dependent   = new List <Expression>();

            foreach (Expression i in M.Terms)
            {
                if (i.DependsOn(x))
                {
                    dependent.Add(i);
                }
                else
                {
                    independent.Add(i);
                }
            }
            if (dependent.Count == 0)
            {
                return(0);
            }

            List <Expression> products = new List <Expression>(dependent.Count);

            foreach (Expression i in dependent)
            {
                List <Expression> terms = new List <Expression>(dependent.Count);
                foreach (Expression j in dependent)
                {
                    if (ReferenceEquals(i, j))
                    {
                        terms.Add(Visit(i));
                    }
                    else
                    {
                        terms.Add(j);
                    }
                }
                products.Add(Product.New(terms));
            }
            return(Product.New(Product.New(independent), Sum.New(products)).Evaluate());
        }
Exemplo n.º 11
0
        protected override Expression VisitPower(Power P)
        {
            Expression f = P.Left;
            Expression g = P.Right;

            if (g.DependsOn(x))
            {
                // f(x)^g(x)
                return(Product.New(P,
                                   Sum.New(
                                       Product.New(Visit(f), Binary.Divide(g, f)),
                                       Product.New(Visit(g), Call.Ln(f)))).Evaluate());
            }
            else
            {
                // f(x)^g
                return(Product.New(
                           g,
                           Power.New(f, Binary.Subtract(g, 1)),
                           Visit(f)).Evaluate());
            }
        }
Exemplo n.º 12
0
        public static Expression EvaluateSum(IEnumerable <Expression> Terms)
        {
            // Map terms to their coefficients.
            DefaultDictionary <Expression, Real> terms = new DefaultDictionary <Expression, Real>(0);

            // Accumulate constants and sum coefficient of each term.
            Real C = 0;

            foreach (Expression i in Terms)
            {
                if (i is Constant)
                {
                    C += (Real)i;
                }
                else
                {
                    // Find constant term.
                    Constant coeff = Product.TermsOf(i).OfType <Constant>().FirstOrDefault();
                    if (!ReferenceEquals(coeff, null))
                    {
                        terms[Product.New(Product.TermsOf(i).ExceptUnique(coeff, Expression.RefComparer))] += (Real)coeff;
                    }
                    else
                    {
                        terms[i] += 1;
                    }
                }
            }

            // Build a new expression with the accumulated terms.
            if (!C.EqualsZero())
            {
                terms.Add(Constant.New(C), (Real)1);
            }
            return(Sum.New(terms
                           .Where(i => !i.Value.EqualsZero())
                           .Select(i => !i.Value.EqualsOne() ? Product.New(i.Key, Constant.New(i.Value)) : i.Key)));
        }
Exemplo n.º 13
0
 public static LazyExpression operator -(LazyExpression L, LazyExpression R)
 {
     return(new LazyExpression(Sum.New(L.value, Unary.Negate(R.value))));
 }
Exemplo n.º 14
0
 // Expression operators.
 public static LazyExpression operator +(Expression L, Expression R)
 {
     return(new LazyExpression(Sum.New(L, R)));
 }
Exemplo n.º 15
0
 // Expression operators.
 public static LazyExpression operator +(LazyExpression L, LazyExpression R)
 {
     return(new LazyExpression(Sum.New(L.value, R.value)));
 }
Exemplo n.º 16
0
 public Expression Solve(Expression x)
 {
     return(Unary.Negate(Sum.New(this.Where(i => !i.Key.Equals(x)).Select(i => Product.New(i.Key, i.Value)))) / this[x]);
 }
Exemplo n.º 17
0
 protected override Expression VisitSum(Sum A)
 {
     return(Sum.New(A.Terms.Select(i => Visit(i)).Where(i => !i.EqualsZero())));
 }
Exemplo n.º 18
0
 public static LazyExpression operator -(Expression L, Expression R)
 {
     return(new LazyExpression(Sum.New(L, Unary.Negate(R))));
 }
Exemplo n.º 19
0
 // V(x + y) = V(x) + V(y)
 protected override Expression VisitSum(Sum A)
 {
     return(Sum.New(A.Terms.Select(i => Visit(i))));
 }