Exemplo n.º 1
0
 // Evaluate x*A, distributing x if A is Add.
 public static Expression Distribute(Expression x, Expression A)
 {
     if (A is Sum || x is Sum)
     {
         return(EvaluateVisitor.EvaluateSum(Sum.TermsOf(A).SelectMany(i => Sum.TermsOf(Distribute(i, x)))));
     }
     else
     {
         return(Product.New(A, x).Evaluate());
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// Create a new linear combination expression equal to x.
        /// </summary>
        /// <param name="B">Basis terms for the linear combination.</param>
        /// <param name="x"></param>
        /// <returns></returns>
        public static LinearCombination New(IEnumerable <Expression> B, Expression x)
        {
            B = B.Buffer();

            LinearCombination ret = new LinearCombination();

            foreach (Expression t in Sum.TermsOf(x.Expand()))
            {
                ret.AddTerm(B, t);
            }
            return(ret);
        }
Exemplo n.º 3
0
            public Equation(Equal Eq, IEnumerable <Expression> Terms)
                : base(0)
            {
                Terms = Terms.AsList();

                Expression f = Eq.Left - Eq.Right;

                foreach (Expression i in Sum.TermsOf(f.Expand()))
                {
                    AddTerm(Terms, i);
                }
            }
Exemplo n.º 4
0
        /// <summary>
        /// Construct a polynomial of x from f(x).
        /// </summary>
        /// <param name="f"></param>
        /// <param name="x"></param>
        /// <returns></returns>
        public static Polynomial New(Expression f, Expression x)
        {
            // Match each term to A*x^N where A is constant with respect to x, and N is an integer.
            Variable   A           = PatternVariable.New("A", i => !i.DependsOn(x));
            Variable   N           = PatternVariable.New("N", i => i.IsInteger());
            Expression TermPattern = Product.New(A, Power.New(x, N));

            DefaultDictionary <int, Expression> P = new DefaultDictionary <int, Expression>(0);

            foreach (Expression i in Sum.TermsOf(f))
            {
                MatchContext Matched = TermPattern.Matches(i, Arrow.New(x, x));
                if (Matched == null)
                {
                    throw new ArgumentException("f is not a polynomial of x.");
                }

                int n = (int)Matched[N];
                P[n] += Matched[A];
            }

            return(new Polynomial(P, x));
        }
Exemplo n.º 5
0
 protected override Expression VisitSum(Sum A)
 {
     return(EvaluateSum(A.Terms.SelectMany(i => Sum.TermsOf(Visit(i)))));
 }