/// <summary> /// Expand a power expression. /// </summary> /// <param name="f"></param> /// <param name="x"></param> /// <returns></returns> private static Expression ExpandPower(Power f, Expression x) { // Get integral exponent of f. int n = Power.IntegralExponentOf(f); // If this is an an integral constant negative exponent, attempt to use partial fractions. if (n < 0 && !ReferenceEquals(x, null)) { Expression b = f.Left.Factor(x); if (n != -1) { b = Power.New(b, Math.Abs(n)); } return(ExpandPartialFractions(1, b, x)); } // If f is an add expression, expand it as if it were multiplication. if (n > 1 && f.Left is Sum) { Expression e = f.Left; for (int i = 1; i < n; ++i) { e = Distribute(f.Left, e); } return(e); } return(f); }
protected override Expression VisitPower(Power P) { Expression L = Visit(P.Left); Expression R = Visit(P.Right); if (R.IsInteger()) { // Transform (x*y)^z => x^z*y^z if z is an integer. Product M = L as Product; if (!ReferenceEquals(M, null)) { return(Visit(Product.New(M.Terms.Select(i => Power.New(i, R))))); } } // Transform (x^y)^z => x^(y*z) if z is an integer. Power LP = L as Power; if (!ReferenceEquals(LP, null)) { L = LP.Left; R = Visit(Product.New(P.Right, LP.Right)); } // Handle identities. Real?LR = AsReal(L); if (EqualsZero(LR)) { return(0); } if (EqualsOne(LR)) { return(1); } Real?RR = AsReal(R); if (EqualsZero(RR)) { return(1); } if (EqualsOne(RR)) { return(L); } // Evaluate result. if (LR != null && RR != null) { return(Constant.New(LR.Value ^ RR.Value)); } else { return(Power.New(L, R)); } }
/// <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); }
/// <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); }
// 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)))); }
// Combine like terms and multiply constants. protected override Expression VisitProduct(Product M) { // Map terms to exponents. DefaultDictionary <Expression, Real> terms = new DefaultDictionary <Expression, Real>(0); // Accumulate constants and sum exponent of each term. Real C = 1; foreach (Expression i in M.Terms.SelectMany(i => Product.TermsOf(Visit(i)))) { if (i is Constant) { Real Ci = (Real)i; // Early exit if 0. if (Ci.EqualsZero()) { return(0); } C *= Ci; } else { Power Pi = i as Power; if (!ReferenceEquals(Pi, null) && Pi.Right is Constant) { terms[Pi.Left] += (Real)Pi.Right; } else { terms[i] += 1; } } } // Build a new expression with the accumulated terms. if (!C.EqualsOne()) { // Find a sum term that has a constant term to distribute into. KeyValuePair <Expression, Real> A = terms.FirstOrDefault(i => Real.Abs(i.Value).EqualsOne() && i.Key is Sum); if (!ReferenceEquals(A.Key, null)) { terms.Remove(A.Key); terms[ExpandExtension.Distribute(C ^ A.Value, A.Key)] += A.Value; } else { terms.Add(C, 1); } } return(Product.New(terms .Where(i => !i.Value.EqualsZero()) .Select(i => !i.Value.EqualsOne() ? Power.New(i.Key, Constant.New(i.Value)) : i.Key))); }
// V((A*x)^n) = A^(1/n)*V(x^n) protected override Expression VisitPower(Power P) { if (!IsConstant(P.Right)) { return(base.VisitPower(P)); } Expression L = P.Left.Factor(); IEnumerable <Expression> A = Product.TermsOf(L).Where(i => IsConstant(i)); if (A.Any()) { return(Product.New(Power.New(Product.New(A), 1 / P.Right), Visit(Product.New(Product.TermsOf(L).Where(i => !IsConstant(i)))))); } return(base.VisitPower(P)); }
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()); } }
/// <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)); }
public static LazyExpression operator /(Expression L, Expression R) { return(new LazyExpression(Product.New(L, Power.New(R, -1)))); }
public static LazyExpression operator /(LazyExpression L, LazyExpression R) { return(new LazyExpression(Product.New(L.value, Power.New(R.value, -1)))); }