Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions BREAKING-CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,28 @@ mpmath's at 4500 digits.
| `Ci(exp(300))` | `0` | `NaN` | below `1e-130`, sign unknown |
| `cos(10^150/3)` | `-0.44819…` | `0.80881903093981837173…` | `0.80881903093981837173…` |

### Simplify's answer is its own answer

**Silent: same values, shorter forms.** `Simplify` gave answers that a second `Simplify` shortened. Numbers in a
product were left unmultiplied, a factor over something was left beside the product, a factor shared by a
quotient was cancelled only in one order of the divisor, and `c ^ (k log(c, a))` became `a ^ k` only where the
logarithm was one of the top two factors of the exponent. Every changed answer has the value it had. A symbolic base
of the logarithm carries `not a = 0 and not a = 1`, as the existing rule does. Of 16,684 generated and random
expressions, 333 gave answers that changed when simplified again; now 11 do, and each of those is the search finding
a different candidate. Measured on master `2a7247653` and on this branch
([#2725](https://github.com/asc-community/AngouriMath/issues/2725)).

| `Simplify` | Was | Now |
|---|---|---|
| `e - (2 * y) * 2` | `e - 2 * 2 * y` | `e - 4 * y` |
| `((-1) - y / 3)^(-1)` | `(-3) * 1 / (3 + y)` | `(-3) / (3 + y)` |
| `((x * 3) * (-1)) / (x * x - 3)` | `3 * (-1) * x / (x ^ 2 - 3)` | `(-3) * x / (x ^ 2 - 3)` |
| `x * ((5 * 3) / pi)` | `x * 15 / pi` | `15 * x / pi` |
| `(e^2)^(1/2) / ((5 - e) * e)` | `e / (e * (5 - e))` | `1 / (5 - e)` |
| `cosh(y * ln(y))` | `(e ^ (-y * ln(y)) + y ^ y) / 2` | `(y ^ y + y ^ (-y)) / 2` |
| `e^(-x * ln(y))` | `e ^ (-x * ln(y))` | `y ^ (-x)` |
| `a^(-x * log(a, y))` | `a ^ (-x * log(a, y))` | `y ^ (-x) provided not a = 0 and not a = 1` |

### A complex value past 10^50 keeps every part of it

**Silent: wrong numbers become right ones.** The complex paths of the exponential, the trigonometric functions and the
Expand Down
25 changes: 25 additions & 0 deletions Sources/AngouriMath/Core/Transformations/Matching/MatchedRules.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3262,6 +3262,19 @@ is var (divided, remainder)
// product and the logarithm that go.
growth: RewriteRuleGrowth.Expands),

// The same three, with the logarithm a factor further down the product, as the sort
// leaves it: e ^ (-ln(y) * y) is e ^ ((-1 * ln(y)) * y).
// https://github.com/asc-community/AngouriMath/issues/2725
new MatchedRule(
"a-base-raised-to-a-product-holding-a-logarithm-of-itself-is-a-power-of-the-antilogarithm",
MatchPattern.Node<Powf>(MatchPattern.Any("c"), MatchPattern.Any<Mulf>("p")),
bound => Functions.Patterns.PowerOfALogarithmAmongFactors(bound["c"], (Mulf)bound["p"])!,
Soundness.SoundUnderAssumptions,
when: bound => Functions.Patterns.PowerOfALogarithmAmongFactors(bound["c"], (Mulf)bound["p"]) is not null,
// Left Unknown: the helper rebuilds the multiplier from however many factors the
// product has, and a symbolic base adds a condition.
description: "a ^ ((m * log(a, b)) * n) = b ^ (m * n)"),

// Four `switch` arms: the power on either side of a product, and the shared base in
// either position inside it. A commutative pattern says both halves at once.
new MatchedRule(
Expand Down Expand Up @@ -3927,6 +3940,18 @@ is var (divided, remainder)
// Left Unknown: the condition attached carries a copy of c, so the delta is
// 2 - |c| -- larger at a leaf, smaller from three nodes up.
description: "(num * c) / (c * den) = num / den, provided c is not zero"),
new MatchedRule(
"a-factor-cancels-out-of-a-product-it-divides",
MatchPattern.Node<Divf>(MatchPattern.Any("c"), MatchPattern.Commutative<Mulf>(MatchPattern.Any("c"), MatchPattern.Any("den"))),
// The same two assumptions as (keep * c) / c. Without it the cancellation depended
// on the order of the divisor's factors.
// https://github.com/asc-community/AngouriMath/issues/2725
bound => (1 / bound["den"]).Provided(
!bound["c"].EqualTo(Integer.Zero) & bound["c"].DomainCondition),
Soundness.SoundUnderAssumptions,
// Left Unknown: the condition attached carries a copy of c and c's own domain
// condition, whose size nothing here bounds.
description: "c / (c * den) = 1 / den, provided c is not zero and is defined"),
new MatchedRule(
"a-difference-over-its-own-reverse-is-minus-one",
MatchPattern.Node<Divf>(MatchPattern.Node<Minusf>(MatchPattern.Any("a"), MatchPattern.Any("b")), MatchPattern.Node<Minusf>(MatchPattern.Any("b"), MatchPattern.Any("a"))),
Expand Down
14 changes: 7 additions & 7 deletions Sources/AngouriMath/Docs/Contributing/WritingARule.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ effect". This is how to supply those seven things.
## Where a rule goes

`Core/Transformations/Matching/MatchedRules.cs`, as a value in a `MatchedRuleSet`. **33** sets and
**343** rules live there today.
**345** rules live there today.

The `switch` statements in `Functions/Simplification/Patterns` are the older form. **All thirty
registered sets now run as data and describe what they run**; none executes its `switch` any more.
Expand Down Expand Up @@ -64,7 +64,7 @@ in a name and putting the identity in brackets after it:
2. Tangent is sine over cosine (tan(a) = sin(a) / cos(a)), so tan(x) becomes sin(x) / cos(x).
```

So the name has to be a clause that survives being read that way. **All 314 distinct rule names are,
So the name has to be a clause that survives being read that way. **All 316 distinct rule names are,
and `StepAsASentenceTest` holds them to it** — a name with a capital, a bracket or an underscore
fails that test rather than degrading the prose quietly.

Expand All @@ -91,7 +91,7 @@ debugged for an afternoon.
| `Left.ToString()` | `Divf(var a, Divf(var b, var c))` — how the matcher spells it |

Write the identity with `=`, not `->`: it is an equality, and the arrow belongs to the direction the
rule happens to be applied in. **340** rules carry one today; a new rule should.
rule happens to be applied in. **342** rules carry one today; a new rule should.

## The pattern language

Expand Down Expand Up @@ -123,7 +123,7 @@ matches and silently builds nothing. `BuildableNodeTypesTest` is the list.

## Replacement: a pattern, or code

**42** of the 343 rules have a pattern on both sides. The rest build their answer in code, and both
**42** of the 345 rules have a pattern on both sides. The rest build their answer in code, and both
are legitimate — but the choice costs two things, so make it deliberately.

A pattern replacement gets:
Expand All @@ -138,7 +138,7 @@ A pattern replacement gets:
- **an exact growth**, counted from the two patterns rather than declared.

A code replacement gets neither, and its growth is `Unknown` unless you declare one. That is the
honest default — **126** rules sit at `Unknown` — but declare it where you can justify it:
honest default — **128** rules sit at `Unknown` — but declare it where you can justify it:

```csharp
// The Chebyshev expansion of sin(n * a) is a sum of n terms where the pattern is one node,
Expand Down Expand Up @@ -227,7 +227,7 @@ limit, against nothing for handing the node over.
| `SoundUnderAssumptions` | holds given something the rule does not check |
| `Heuristic` | usually right |

**192** of the 343 rules are `Sound` and **151** are conditional. Every one of the thirty registered
**192** of the 345 rules are `Sound` and **153** are conditional. Every one of the thirty registered
*sets* declares `SoundUnderAssumptions`, because a set's tier is the **minimum** over its rules — so
the set grain says nothing and the rule grain says everything. A derivation reports the rule's tier
(`RewriteStep.Soundness`), which is why getting it right matters beyond the label.
Expand All @@ -244,7 +244,7 @@ first decides the answer**. Two cases, and only one of them is a decision:
everything `Mulf(Divf(a, b), Divf(c, d))` matches and more, so the general rule would swallow the
special one and the special one would never fire. `MatchPattern.Subsumes` computes this and
`MatchedRuleSet.RulesByPriority` applies it: the specific rule is tried first because of what the two
patterns *are*, not because of where you typed them. **30** rule pairs are ordered that way.
patterns *are*, not because of where you typed them. **33** rule pairs are ordered that way.

**Where neither subsumes the other, the order is a bare choice and nothing but your placement makes
it.** There are **39** such conflicts, and `RulePriorityTest` records every one by name. If your rule
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,16 @@ internal static Integer DenominatorOf(Entity entity)
Divf(Mulf(var any2, var any1), Mulf(var any2a, var any3)) when any2 == any2a => (any1 / any3).Provided(!any2.EqualTo(Integer.Zero)),
Divf(Mulf(var any2, var any1), Mulf(var any3, var any2a)) when any2 == any2a => (any1 / any3).Provided(!any2.EqualTo(Integer.Zero)),

// c / (c * d) and c / (d * c): the factor shared with the whole numerator, under the
// same two assumptions as (a * c) / c. Without it the cancellation depended on the
// order the divisor's factors came in, and Simplify left pi / ((5 - pi) * pi) as it
// was and cancelled pi / (pi * (5 - pi)), which is the same tree in print order.
// https://github.com/asc-community/AngouriMath/issues/2725
Divf(var any2, Mulf(var any2a, var any1)) when any2 == any2a =>
(1 / any1).Provided(!any2.EqualTo(Integer.Zero) & any2.DomainCondition),
Divf(var any2, Mulf(var any1, var any2a)) when any2 == any2a =>
(1 / any1).Provided(!any2.EqualTo(Integer.Zero) & any2.DomainCondition),

// ({1} - {2}) / ({2} - {1})
Divf(Minusf(var any1, var any2), Minusf(var any2a, var any1a) denom) when (any1, any2) == (any1a, any2a) => new Providedf(-1, !denom.EqualTo(0)),

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,9 @@ internal static bool IsWholeOrAnOddRoot(Number n) =>
Powf(var base1, Mulf(Logf(var base1a, var any1), var k))
when base1 == base1a && base1 is not Number and not Constant
=> new Powf(any1, k).Provided(!base1.EqualTo(0) & !base1.EqualTo(1)),
// And with the logarithm a factor further down the product, as the sort leaves it:
// e ^ (-ln(y) * y) is (-1 * ln(y)) * y. https://github.com/asc-community/AngouriMath/issues/2725
Powf(var base1, Mulf exponent) when PowerOfALogarithmAmongFactors(base1, exponent) is { } power => power,

Mulf(Powf(var any1, var any3), Mulf(var any1a, var any2)) when any1 == any1a => new Powf(any1, any3 + 1) * any2,
Mulf(Powf(var any1, var any3), Mulf(var any2, var any1a)) when any1 == any1a => new Powf(any1, any3 + 1) * any2,
Expand Down Expand Up @@ -450,6 +453,51 @@ internal static Entity GatherPowersOfOneBase(Entity x)
private static bool IsPositiveReal(Entity entity)
=> entity.Evaled is Real { EDecimal.IsFinite: true } value && value.IsPositive;

/// <summary>
/// <c>c ^ (k * log(c, a))</c> written <c>a ^ k</c> where the logarithm is a factor of the
/// product below its top, as in <c>(m * log(c, a)) * n</c>: the arms above read it only as
/// one of the top two operands. <see langword="null"/> where it is one of those, where no
/// factor or more than one is a logarithm to the base <c>c</c>, and where <c>c</c> is 0 or
/// 1. A symbolic base carries <c>c</c> neither 0 nor 1 as the answer's condition, as the
/// arms above do. https://github.com/asc-community/AngouriMath/issues/2725
/// </summary>
internal static Entity? PowerOfALogarithmAmongFactors(Entity @base, Mulf exponent)
{
if (exponent.Multiplier is Logf || exponent.Multiplicand is Logf
|| @base is Number number && (number == Integer.Zero || number == Integer.One))
return null;
var factors = new System.Collections.Generic.List<Entity>();
Gather(exponent, factors);
var at = -1;
for (var i = 0; i < factors.Count; i++)
if (factors[i] is Logf(var logBase, _) && logBase == @base)
{
if (at >= 0)
return null;
at = i;
}
if (at < 0)
return null;
var antilogarithm = ((Logf)factors[at]).Antilogarithm;
factors.RemoveAt(at);
var k = factors[0];
for (var i = 1; i < factors.Count; i++)
k *= factors[i];
var power = new Powf(antilogarithm, k);
return @base is Number or Constant ? power : power.Provided(!@base.EqualTo(0) & !@base.EqualTo(1));

static void Gather(Entity node, System.Collections.Generic.List<Entity> into)
{
if (node is Mulf(var left, var right))
{
Gather(left, into);
Gather(right, into);
}
else
into.Add(node);
}
}

/// <summary>
/// Whether <paramref name="literal"/> lies strictly between 0 and 1, so that its logarithm
/// is minus that of its reciprocal. https://github.com/asc-community/AngouriMath/issues/2617
Expand Down
56 changes: 40 additions & 16 deletions Sources/AngouriMath/Functions/Simplification/Simplificator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -199,39 +199,63 @@ internal static Entity InPrintOrder(Entity expression)
private static Entity FactorsInPrintOrder(Entity.Mulf product)
{
// Read before anything is built: this runs on every answer, and most products are
// in order already.
// in order already, with one number at most and no quotient by a number's worth.
var highest = 0;
if (InOrder(product, ref highest))
var numbers = 0;
if (InOrder(product, ref highest, ref numbers))
return product;
var factors = new System.Collections.Generic.List<Entity>();
Gather(product, factors);
// A product with a transpose or a vector product in it, or a factor built from one, is a product of
// matrices, which do not commute. https://github.com/asc-community/AngouriMath/issues/2147
if (factors.Exists(static factor => factor is Entity.Transposef or Entity.Powf(Entity.Transposef, _)
|| ProductsOfMatrices.IsAMatrixNotWrittenOut(factor)))
if (factors.Exists(static factor => IsAMatrixFactor(factor)
|| factor is Entity.Divf(var dividend, var divisor) && (IsAMatrixFactor(dividend) || IsAMatrixFactor(divisor))))
return product;
var ordered = new System.Collections.Generic.List<Entity>(factors.Count);
// The numbers multiplied together, and a factor over something taken as a division by
// it: 2 * y * 2 is 4 y, and 3 * (1 / s) is 3 / s. Both are the same value with the
// same domain in fewer nodes, which is what the search would have preferred had it met
// that shape; it met the factors apart, or a quotient beside them, and only this pass
// brings them together. Left as they were, Simplify asked again of its own answer
// gave a different one. https://github.com/asc-community/AngouriMath/issues/2725
Entity? coefficient = null;
var divisors = new System.Collections.Generic.List<Entity>();
var rest = new System.Collections.Generic.List<Entity>(factors.Count);
foreach (var factor in factors)
{
var numerator = factor;
if (factor is Entity.Divf(var dividend, var divisor) && dividend is Entity.Number)
{
divisors.Add(divisor);
numerator = dividend;
}
if (numerator is Entity.Number number)
coefficient = coefficient is null ? number : (coefficient * number).InnerSimplified;
else
rest.Add(numerator);
}
var ordered = new System.Collections.Generic.List<Entity>(rest.Count + 1);
if (coefficient is not null && (coefficient != Entity.Number.Integer.One || rest.Count == 0))
ordered.Add(coefficient);
for (var rank = 0; rank <= 2; rank++)
foreach (var factor in factors)
foreach (var factor in rest)
if (FactorRank(factor) == rank)
ordered.Add(factor);
// A number brought to the front of a quotient over a number is that quotient's
// numerator: 2 * (1 / s) is written 2 / s rather than 2 * 1 / s.
if (ordered.Count > 1 && ordered[0] is Entity.Number number
&& ordered[1] is Entity.Divf(Entity.Number numerator, var divisor))
{
ordered[1] = new Entity.Divf((number * numerator).InnerSimplified, divisor);
ordered.RemoveAt(0);
}
Entity rebuilt = ordered[0];
for (var j = 1; j < ordered.Count; j++)
rebuilt = new Entity.Mulf(rebuilt, ordered[j]);
foreach (var divisor in divisors)
rebuilt = new Entity.Divf(rebuilt, divisor);
return rebuilt;

static bool InOrder(Entity node, ref int highest)
static bool IsAMatrixFactor(Entity factor)
=> factor is Entity.Transposef or Entity.Powf(Entity.Transposef, _) || ProductsOfMatrices.IsAMatrixNotWrittenOut(factor);

static bool InOrder(Entity node, ref int highest, ref int numbers)
{
if (node is Entity.Mulf(var left, var right))
return InOrder(left, ref highest) && InOrder(right, ref highest);
return InOrder(left, ref highest, ref numbers) && InOrder(right, ref highest, ref numbers);
if (node is Entity.Divf(Entity.Number, _) || node is Entity.Number && ++numbers > 1)
return false;
var rank = FactorRank(node);
if (rank < highest)
return false;
Expand Down
Loading
Loading