Skip to content

Commit 5f1e85a

Browse files
The LINQ compiler gives a constant, a nullable operand and sgn(0) the value evaluation gives (#2242)
Three defects in the LINQ compiler, found by work/compilesweep. A constant over Complex (#2235). A constant is compiled as the narrowest type that holds it, -1 as a long, and a function widens a long only to double. So in an expression compiled over Complex, sqrt(-1), ln(-1) and arcsin(2) were Math's NaN, widened to (NaN, 0), and 1/0 was +oo, where evaluation has no value. FastExpression, whose constants are Complex, was right. Where any argument or the result is Complex, BuildTree now converts each constant to Complex. Over double, a value that is not real still has none. A nullable operand (#2237). An Iverson bracket compiles to an int?, and a provided integer constant to a long?. No function has a definition for either, and the widening table has neither. So tan(iverson(pi > 0)) threw KeyNotFoundException, and abs, floor and sgn of one threw AngouriBugException, which asks for a bug report. The unary and binary converters now take a nullable number as a double, NaN for none, before anything else. A statement's bool? stays as it is. sgn(0) over Complex (#2238). The definition was z / |z|, which is 0/0 at 0. It is the Signum extension FastExpression already used, which is 0 there. LinqCompilationValueTest compares LINQ over Complex and FastExpression with evaluation on 16 expressions, among them six constants whose values are not real, 1/0, five nullable operands and sgn at 0. It also checks the double compiler on both kinds. 17 of its 21 cases fail on master. sgn(-1 provided false) is left out: evaluation gives 1 there, which is wrong, and is #2241. Fixes #2235. Fixes #2237. Fixes #2238. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 5d4a300 commit 5f1e85a

7 files changed

Lines changed: 132 additions & 11 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,24 @@ one where both sides are real, and `NaN` where either is not
431431
|---|---|---|
432432
| `"x mod 3".ToEntity().Compile<Complex, Complex>("x")(7)` | `UncompilableNodeException` | `(1, 0)` |
433433

434+
### The LINQ compiler gives a constant, a nullable operand and `sgn(0)` the value evaluation gives
435+
436+
**Silent: three compiled values over `Complex` are evaluation's, and one compile that threw compiles.**
437+
- A constant is taken over `Complex` where the expression is compiled over it. As a `long`, a constant widened only
438+
to `double`, so `sqrt(-1)`, `ln(-1)` and `arcsin(2)` were `NaN` and `1/0` was `+oo`
439+
([#2235](https://github.com/asc-community/AngouriMath/issues/2235)).
440+
- An Iverson bracket, an `int?`, and a `provided` integer, a `long?`, are widened to `double` before a function takes
441+
them. They threw `KeyNotFoundException` or `AngouriBugException`
442+
([#2237](https://github.com/asc-community/AngouriMath/issues/2237)).
443+
- `sgn(0)` is `0`, where `z / |z|` made it `NaN` ([#2238](https://github.com/asc-community/AngouriMath/issues/2238)).
444+
445+
| Input | Was (2.6.0) | Now |
446+
|---|---|---|
447+
| `"x + sqrt(-1)".ToEntity().Compile<Complex, Complex>("x")(0)` | `(NaN, 0)` | `(6.123233995736766E-17, 1)` |
448+
| `"x + 1/0".ToEntity().Compile<Complex, Complex>("x")(0)` | `(Infinity, 0)` | `(NaN, NaN)` |
449+
| `"x + sgn(-1 provided pi > 3)".ToEntity().Compile<Complex, Complex>("x")(1)` | throws `AngouriBugException` | `(0, 0)` |
450+
| `"sgn(x)".ToEntity().Compile<Complex, Complex>("x")(0)` | `(NaN, NaN)` | `(0, 0)` |
451+
434452
### A compiled product of real numbers is real at an infinity
435453

436454
**Silent: a compiled product or quotient with a real infinity is that infinity, where it had a `NaN` imaginary part.**

‎Sources/.editorconfig‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,9 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed
393393
[Tests/UnitTests/Common/CongruenceCompilationTest.cs]
394394
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
395395

396+
[Tests/UnitTests/Common/LinqCompilationValueTest.cs]
397+
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
398+
396399
[Tests/UnitTests/Common/CompileMatrixTest.cs]
397400
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
398401

‎Sources/AngouriMath/Functions/Compilation/IntoLinq/CompilationProtocol.cs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ public virtual Expression ConvertType(Expression expr, Type type)
130130
/// </summary>
131131
public virtual Expression ConvertUnaryNode(Expression e, Entity typeHolder)
132132
{
133+
e = NumericOperand(e);
133134
// A function of a matrix has no compiled form here: the tensor operations are the
134135
// arithmetic ones, and sin(A) is not an element-by-element sine of a matrix.
135136
if (TensorCompilation.IsTensor(e.Type))
@@ -207,6 +208,15 @@ Imf when ShouldBeAtLeastDouble(e) is var newE => Expression.Call(GetDef("
207208
};
208209
}
209210

211+
// A number that may have no value, an Iverson bracket's int? or a provided integer's long?, as a double, which
212+
// has NaN for none: no function takes the nullable integer, and widening one threw KeyNotFoundException or
213+
// AngouriBugException. A statement's bool? stays itself. https://github.com/asc-community/AngouriMath/issues/2237
214+
private Expression NumericOperand(Expression expr)
215+
=> Nullable.GetUnderlyingType(expr.Type) is { } underlying && underlying != typeof(bool)
216+
&& underlying != typeof(System.Numerics.Complex) && underlying != typeof(double)
217+
? ConvertType(expr, typeof(double))
218+
: expr;
219+
210220
private Expression ShouldBeAtLeastDouble(Expression expr)
211221
{
212222
if (typeLevelInHierarchy[expr.Type] < typeLevelInHierarchy[typeof(double)])
@@ -226,7 +236,7 @@ public virtual Expression ConvertBinaryNode(Expression left, Expression right, E
226236
?? throw new UncompilableNodeException(
227237
$"The node of type {typeHolder.GetType()} has no compiled form over a matrix.");
228238

229-
(left, right) = EqualizeTypesIfAble(left, right);
239+
(left, right) = EqualizeTypesIfAble(NumericOperand(left), NumericOperand(right));
230240
return typeHolder switch
231241
{
232242
Sumf => Operator(ExpressionType.Add, left, right),

‎Sources/AngouriMath/Functions/Compilation/IntoLinq/IntoLinqCompiler.cs‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,12 @@ internal static TDelegate Compile<TDelegate>(
4747
// https://github.com/asc-community/AngouriMath/issues/894
4848
try
4949
{
50-
var tree = BuildTree(expr, subexpressionsCache, variableAssignments, localVars, protocol);
50+
// Over Complex a constant is a Complex too, so that a function of it is taken over Complex: as a long,
51+
// sqrt(-1) widened only to double and was NaN. https://github.com/asc-community/AngouriMath/issues/2235
52+
var constantType = typesAndNames.Any(c => c.type == typeof(System.Numerics.Complex)) || returnType == typeof(System.Numerics.Complex)
53+
? typeof(System.Numerics.Complex)
54+
: null;
55+
var tree = BuildTree(expr, subexpressionsCache, variableAssignments, localVars, protocol, constantType);
5156
var treeWithLocals = Expression.Block(localVars, variableAssignments.Append(tree));
5257
Expression entireExpression = returnType is not null ? protocol.ConvertType(treeWithLocals, returnType) : treeWithLocals;
5358
var finalLambda = Expression.Lambda<TDelegate>(entireExpression, functionArguments);
@@ -68,15 +73,16 @@ internal static Expression BuildTree(
6873
Dictionary<Entity, ParameterExpression> cachedSubexpressions,
6974
List<Expression> variableAssignments,
7075
List<ParameterExpression> newLocalVars,
71-
CompilationProtocol protocol)
76+
CompilationProtocol protocol,
77+
Type? constantType = null)
7278
{
7379
if (cachedSubexpressions.TryGetValue(expr, out var readyVar))
7480
return readyVar;
7581

7682
Expression subTree = expr switch
7783
{
7884
Variable { IsConstant: true } c
79-
=> BuildTree(c.Evaled, cachedSubexpressions, variableAssignments, newLocalVars, protocol),
85+
=> BuildTree(c.Evaled, cachedSubexpressions, variableAssignments, newLocalVars, protocol, constantType),
8086

8187
// A compiled expression is a function of the variables it was compiled over,
8288
// so one it does not mention is not something it can be given a value for.
@@ -90,26 +96,27 @@ internal static Expression BuildTree(
9096
? $", which are {string.Join(", ", over)}"
9197
: ", which are none")),
9298

99+
Number when constantType is { } type => protocol.ConvertType(protocol.ConvertConstant(expr), type),
93100
Entity.Boolean or Number => protocol.ConvertConstant(expr),
94101

95102
IUnaryNode oneArg
96103
=> protocol.ConvertUnaryNode(
97-
BuildTree(oneArg.NodeChild, cachedSubexpressions, variableAssignments, newLocalVars, protocol),
104+
BuildTree(oneArg.NodeChild, cachedSubexpressions, variableAssignments, newLocalVars, protocol, constantType),
98105
expr),
99106

100107
// A membership in a set of numbers, the set not being a value: only the element is computed.
101108
// https://github.com/asc-community/AngouriMath/issues/2195
102109
Set.Inf(var element, Set.SpecialSet special) when AngouriMath.Numerics.NumberStatements.Of(special) is { } set
103110
=> protocol.ConvertMembership(
104-
BuildTree(element, cachedSubexpressions, variableAssignments, newLocalVars, protocol), set),
111+
BuildTree(element, cachedSubexpressions, variableAssignments, newLocalVars, protocol, constantType), set),
105112

106113
IBinaryNode twoArg
107114
=> protocol.ConvertBinaryNode(
108-
BuildTree(twoArg.NodeFirstChild, cachedSubexpressions, variableAssignments, newLocalVars, protocol),
109-
BuildTree(twoArg.NodeSecondChild, cachedSubexpressions, variableAssignments, newLocalVars, protocol),
115+
BuildTree(twoArg.NodeFirstChild, cachedSubexpressions, variableAssignments, newLocalVars, protocol, constantType),
116+
BuildTree(twoArg.NodeSecondChild, cachedSubexpressions, variableAssignments, newLocalVars, protocol, constantType),
110117
expr),
111118

112-
var other => protocol.ConvertOtherNode(other.DirectChildren.Select(c => BuildTree(c, cachedSubexpressions, variableAssignments, newLocalVars, protocol)), expr)
119+
var other => protocol.ConvertOtherNode(other.DirectChildren.Select(c => BuildTree(c, cachedSubexpressions, variableAssignments, newLocalVars, protocol, constantType)), expr)
113120
};
114121

115122
var newVar = Expression.Variable(subTree.Type);

‎Sources/AngouriMath/Functions/Compilation/IntoLinq/MathAllMethods.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,8 @@ public static BigInteger Acsc(BigInteger a)
234234
public static int Abs(int a) => Math.Abs(a);
235235
public static BigInteger Abs(BigInteger a) => BigInteger.Abs(a);
236236

237-
public static System.Numerics.Complex Sgn(System.Numerics.Complex a) => a / System.Numerics.Complex.Abs(a);
237+
// 0 at 0, where a / |a| is 0/0: https://github.com/asc-community/AngouriMath/issues/2238
238+
public static System.Numerics.Complex Sgn(System.Numerics.Complex a) => AngouriMath.InternalAMExtensions.Signum(a);
238239
public static double Sgn(double a) => a switch { > 0 or double.PositiveInfinity => 1, 0 => 0, < 0 or double.NegativeInfinity => -1, _ => double.NaN };
239240
public static float Sgn(float a) => a switch { > 0 or float.PositiveInfinity => 1, 0 => 0, < 0 or float.NegativeInfinity => -1, _ => float.NaN };
240241
public static long Sgn(long a) => a switch { > 0 => 1, 0 => 0, < 0 => -1 };

‎Sources/AngouriMath/Functions/Compilation/IntoLinq/MathAllMethods.tt‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,8 @@ namespace AngouriMath.Core.Compilation.IntoLinq
153153
public static int Abs(int a) => Math.Abs(a);
154154
public static BigInteger Abs(BigInteger a) => BigInteger.Abs(a);
155155

156-
public static System.Numerics.Complex Sgn(System.Numerics.Complex a) => a / System.Numerics.Complex.Abs(a);
156+
// 0 at 0, where a / |a| is 0/0: https://github.com/asc-community/AngouriMath/issues/2238
157+
public static System.Numerics.Complex Sgn(System.Numerics.Complex a) => AngouriMath.InternalAMExtensions.Signum(a);
157158
public static double Sgn(double a) => a switch { > 0 or double.PositiveInfinity => 1, 0 => 0, < 0 or double.NegativeInfinity => -1, _ => double.NaN };
158159
public static float Sgn(float a) => a switch { > 0 or float.PositiveInfinity => 1, 0 => 0, < 0 or float.NegativeInfinity => -1, _ => float.NaN };
159160
public static long Sgn(long a) => a switch { > 0 => 1, 0 => 0, < 0 => -1 };
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
//
2+
// Copyright (c) 2019-2026 Angouri.
3+
// AngouriMath is licensed under MIT.
4+
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
5+
// Website: https://am.angouri.org.
6+
//
7+
8+
using System.Numerics;
9+
using AngouriMath;
10+
using AngouriMath.Extensions;
11+
using Xunit;
12+
13+
namespace AngouriMath.Tests.Common
14+
{
15+
/// <summary>
16+
/// The LINQ compiler gives what evaluation and FastExpression give, where it did not: a constant whose value is
17+
/// not real, over <c>Complex</c> (<a href="https://github.com/asc-community/AngouriMath/issues/2235">#2235</a>); an
18+
/// Iverson bracket or a provided integer inside a function
19+
/// (<a href="https://github.com/asc-community/AngouriMath/issues/2237">#2237</a>); and <c>sgn(0)</c>
20+
/// (<a href="https://github.com/asc-community/AngouriMath/issues/2238">#2238</a>).
21+
/// </summary>
22+
[Trait("Area", "Common")]
23+
public sealed class LinqCompilationValueTest
24+
{
25+
private static Complex Evaluated(string expression, Complex x)
26+
=> ((Entity.Number.Complex)expression.ToEntity().Substitute("x", (Entity.Number.Complex)x).Evaled).ToNumerics();
27+
28+
private static bool Agree(Complex expected, Complex actual)
29+
=> double.IsNaN(expected.Real) || double.IsNaN(expected.Imaginary)
30+
? double.IsNaN(actual.Real) || double.IsNaN(actual.Imaginary)
31+
: Complex.Abs(expected - actual) <= 1e-12 * System.Math.Max(1, Complex.Abs(expected));
32+
33+
[Theory]
34+
// A constant whose value is not real: it was taken over double, and NaN.
35+
[InlineData("x + sqrt(-1)", 0)]
36+
[InlineData("x + ln(-1)", 0)]
37+
[InlineData("x + arcsin(2)", 0)]
38+
[InlineData("x + arccos(-2)", 1)]
39+
[InlineData("x * sqrt(-4)", 1)]
40+
[InlineData("x + (-8)^(1/4)", 0)]
41+
// 1/0 has no value, where over double it was +oo.
42+
[InlineData("x + 1/0", 0)]
43+
// An Iverson bracket and a provided integer inside a function.
44+
[InlineData("x + tan(iverson(pi > 0))", 1)]
45+
[InlineData("x + abs(iverson(e > 3))", 1)]
46+
[InlineData("x + floor(iverson(x > 0))", 1)]
47+
[InlineData("x + sgn(-1 provided pi > 3)", 1)]
48+
[InlineData("max(iverson(x > 0), 1/2) + x", -1)]
49+
// sgn(0) is 0.
50+
[InlineData("sgn(x)", 0)]
51+
[InlineData("sgn(x - x)", 1)]
52+
[InlineData("sgn(x)", -3)]
53+
public void OverComplexItIsWhatEvaluationAndFastExpressionGive(string expression, double at)
54+
{
55+
var expected = Evaluated(expression, at);
56+
var linq = expression.ToEntity().Compile<Complex, Complex>("x")(at);
57+
var fast = expression.ToEntity().Compile("x").Call(at);
58+
Assert.True(Agree(expected, linq), $"{expression} at {at}: {expected} evaluated, {linq} by LINQ");
59+
Assert.True(Agree(expected, fast), $"{expression} at {at}: {expected} evaluated, {fast} by FastExpression");
60+
}
61+
62+
/// <summary>A constant is taken over Complex where the result is one, whatever the argument's type.</summary>
63+
[Fact]
64+
public void ToAComplexResultAConstantIsComplex()
65+
=> Assert.True(Agree(new Complex(2, 1), "x + sqrt(-1)".ToEntity().Compile<double, Complex>("x")(2)));
66+
67+
/// <summary>Over double a value that is not real has none, as before.</summary>
68+
[Theory]
69+
[InlineData("x + sqrt(-1)", 0)]
70+
[InlineData("x + ln(-1)", 0)]
71+
public void OverDoubleAValueThatIsNotRealIsNaN(string expression, double at)
72+
=> Assert.True(double.IsNaN(expression.ToEntity().Compile<double, double>("x")(at)));
73+
74+
[Theory]
75+
[InlineData("x + tan(iverson(pi > 0))", 1)]
76+
[InlineData("x + floor(iverson(x > 0))", 1)]
77+
[InlineData("x + sgn(-1 provided pi > 3)", 1)]
78+
public void OverDoubleANullableOperandIsWhatEvaluationGives(string expression, double at)
79+
=> Assert.True(Agree(Evaluated(expression, at), expression.ToEntity().Compile<double, double>("x")(at)));
80+
}
81+
}

0 commit comments

Comments
 (0)