diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index e4ccd9325..0b16b4971 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -533,6 +533,33 @@ already did. With downcasting on, nothing changes ([#2622](https://github.com/as | `(-30.5)^(1/3)` | `1.562… + 2.705…i` | `-3.124…` | | `(-30.5)^(1/2)` | `5.522…i` | unchanged | +### A compiled integer of 2^63 or more is its nearest double, and a BigInteger converts to the nearest double + +**Not silent: an exception becomes a value. Silent: wrong values become right ones.** `Compile` read every +integer constant as a `long`, so one of 2^63 or more threw `OverflowException` whatever type was compiled to. It is now +a `BigInteger`, exact over `BigInteger`, and over `double` and `Complex` the nearest double, `±Infinity` beyond their +range, which is what evaluating it and casting to `double` give. A `BigInteger` argument or value converted to `double`, +`float` or `Complex` was truncated by the runtime's conversion; it is rounded to the nearest now. Over a matrix of `int` +a constant past `int` was wrapped, and over one of `long` a constant past `long` threw; the matrix is widened to the +constant's type now, as it already was beside a `double`, so a compile that asks for an `int[,]` result of such a +constant refuses with `UncompilableNodeException` where it wrapped, and one that asks for `long[,]` answers. Beside a +`long` argument a matrix of `int` keeps its type, as before. Measured on master `2a7247653` and on this branch +([#2720](https://github.com/asc-community/AngouriMath/issues/2720)). + +| | Was | Now | +|---|---|---| +| `"100000000000000000000 * x".Compile("x")(2)`, and over `Complex` | throws `OverflowException` | `2E+20` | +| `"x + 12345678901234567890"` over `double` at 0 | throws `OverflowException` | `1.2345678901234567E+19` | +| `10^400` written out, `* x` over `double` at 2 | throws `OverflowException` | `+Infinity` | +| `"x".Compile("x")` at `2^63 - 1` | `9.223372036854775E+18` | `9.223372036854776E+18` | +| the same at `10^40` | `9.999999999999999E+39` | `1E+40` | +| `"trace(A * 4294967296)".Compile("A")` at `[[1, 2], [3, 4]]` | `0` | `21474836480` | +| `"trace(A * 2147483648)"`, the same | `-2147483648` | `10737418240` | +| `"trace(A * 100000000000000000000)"` over `long[,]` | throws `OverflowException` | `5E+20` | +| `"A * 4294967296".Compile("A")` | `[[0, 0], [0, 0]]` | throws `UncompilableNodeException` | +| `"A * 4294967296".Compile("A")` | throws `UncompilableNodeException` | `[[4294967296, 8589934592], [12884901888, 17179869184]]` | +| `"A * n".Compile("A", "n")` at `n = 3` | `[[3, 6], [9, 12]]` | unchanged | + ### A singular matrix is not inverted because its determinant is not written as 0 **Not silent: a wrong answer is now no answer.** `Matrix.Inverse`, `Matrix.Pow` with a negative exponent, `M^(-1)` and diff --git a/Sources/.editorconfig b/Sources/.editorconfig index fdd52020c..b2fcdbc54 100644 --- a/Sources/.editorconfig +++ b/Sources/.editorconfig @@ -1151,6 +1151,12 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed [AngouriMath/Functions/Compilation/RealProducts.cs] 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 +[AngouriMath/Functions/Compilation/BigIntegerConversions.cs] +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 + +[Tests/UnitTests/Common/ACompiledIntegerBeyondLongTest.cs] +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 + [Tests/UnitTests/Common/RealProductCompilationTest.cs] 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 diff --git a/Sources/AngouriMath/Functions/Compilation/BigIntegerConversions.cs b/Sources/AngouriMath/Functions/Compilation/BigIntegerConversions.cs new file mode 100644 index 000000000..6f2559fa3 --- /dev/null +++ b/Sources/AngouriMath/Functions/Compilation/BigIntegerConversions.cs @@ -0,0 +1,36 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System.Numerics; +using PeterO.Numbers; + +namespace AngouriMath.Core.Compilation +{ + /// + /// A as the nearest , or + /// , an infinity beyond their range, as evaluation rounds an integer. The runtime's own + /// conversions truncate past the longs: 2^63 - 1 was 2^63 - 1024, where the nearest double is 2^63. + /// https://github.com/asc-community/AngouriMath/issues/2720 + /// + internal static class BigIntegerConversions + { + public static double ToDouble(BigInteger value) + => value >= long.MinValue && value <= long.MaxValue + ? (long)value + : Beyond(value).ToDouble(); + + public static float ToSingle(BigInteger value) + => value >= long.MinValue && value <= long.MaxValue + ? (long)value + : Beyond(value).ToSingle(); + + public static System.Numerics.Complex ToComplex(BigInteger value) => new(ToDouble(value), 0); + + private static EFloat Beyond(BigInteger value) + => EFloat.FromEInteger(EInteger.FromBytes(value.ToByteArray(), littleEndian: true)); + } +} diff --git a/Sources/AngouriMath/Functions/Compilation/IntoLinq/CompilationProtocol.cs b/Sources/AngouriMath/Functions/Compilation/IntoLinq/CompilationProtocol.cs index 4915cf092..b2ad9d58b 100644 --- a/Sources/AngouriMath/Functions/Compilation/IntoLinq/CompilationProtocol.cs +++ b/Sources/AngouriMath/Functions/Compilation/IntoLinq/CompilationProtocol.cs @@ -472,10 +472,17 @@ private Expression HandlePiecewise(IEnumerable en) return piecewiseExpr; } + // An integer outside the range of long is a BigInteger, which holds it exactly: the cast to long threw + // OverflowException from 2^63 on, whatever type was being compiled to. Over double and Complex it is the + // nearest double, by BigIntegerConversions. https://github.com/asc-community/AngouriMath/issues/2720 private static object DownCast(Number num) { - if (num is Integer) - return (long)num; + if (num is Integer integer) + { + if (integer.EInteger.CanFitInInt64()) + return integer.EInteger.ToInt64Unchecked(); + return integer.EInteger.ToBigInteger(); + } if (num is Real) return (double)num; if (num is Number.Complex) @@ -524,7 +531,9 @@ private static MethodInfo GetDef(string name, int argCount, Type type) { (typeof(long), typeof(System.Numerics.Complex)), Conv(v => (System.Numerics.Complex)v) }, { (typeof(float), typeof(System.Numerics.Complex)), Conv(v => (System.Numerics.Complex)v) }, { (typeof(double), typeof(System.Numerics.Complex)), Conv(v => (System.Numerics.Complex)v) }, - { (typeof(BigInteger), typeof(System.Numerics.Complex)), Conv(v => (System.Numerics.Complex)v) }, + // The nearest value, where the runtime's conversions truncate past the longs. + // https://github.com/asc-community/AngouriMath/issues/2720 + { (typeof(BigInteger), typeof(System.Numerics.Complex)), Through(v => BigIntegerConversions.ToComplex(v)) }, { (typeof(int), typeof(BigInteger)), Conv(v => (BigInteger)v) }, { (typeof(long), typeof(BigInteger)), Conv(v => (BigInteger)v) }, @@ -533,8 +542,8 @@ private static MethodInfo GetDef(string name, int argCount, Type type) { (typeof(BigInteger), typeof(int)), Conv(v => (int)v) }, { (typeof(BigInteger), typeof(long)), Conv(v => (long)v) }, - { (typeof(BigInteger), typeof(float)), Conv(v => (float)v) }, - { (typeof(BigInteger), typeof(double)), Conv(v => (double)v) }, + { (typeof(BigInteger), typeof(float)), Through(v => BigIntegerConversions.ToSingle(v)) }, + { (typeof(BigInteger), typeof(double)), Through(v => BigIntegerConversions.ToDouble(v)) }, }; /// @@ -559,6 +568,9 @@ private static MethodInfo GetDef(string name, int argCount, Type type) private static MethodInfo Named(Expression> e) => ((MethodCallExpression)e.Body).Method; + private static MethodInfo Through(Expression> e) + => ((MethodCallExpression)e.Body).Method; + private static MethodInfo Conv(Expression> e) => ((UnaryExpression)e.Body).Method ?? throw new AngouriBugException($"{typeof(TFrom)} -> {typeof(TTo)} is not a user-defined conversion"); @@ -675,6 +687,17 @@ private static Expression Coerce(Expression expr, Type type) { var from = Nullable.GetUnderlyingType(expr.Type) ?? expr.Type; var to = Nullable.GetUnderlyingType(type) ?? type; + // An integer constant beyond long, widened once here rather than on every call, by the conversion the + // call would make. https://github.com/asc-community/AngouriMath/issues/2720 + if (expr is ConstantExpression { Value: BigInteger big }) + { + if (to == typeof(double)) + return Expression.Constant(BigIntegerConversions.ToDouble(big), type); + if (to == typeof(float)) + return Expression.Constant(BigIntegerConversions.ToSingle(big), type); + if (to == typeof(System.Numerics.Complex)) + return Expression.Constant(BigIntegerConversions.ToComplex(big), type); + } return conversionOperators.TryGetValue((from, to), out var op) ? Expression.Convert(expr, type, op) : Expression.Convert(expr, type); diff --git a/Sources/AngouriMath/Functions/Compilation/IntoLinq/IntoLinqCompiler.cs b/Sources/AngouriMath/Functions/Compilation/IntoLinq/IntoLinqCompiler.cs index 7a6d858e6..f8a9cf8cc 100644 --- a/Sources/AngouriMath/Functions/Compilation/IntoLinq/IntoLinqCompiler.cs +++ b/Sources/AngouriMath/Functions/Compilation/IntoLinq/IntoLinqCompiler.cs @@ -160,7 +160,10 @@ private static void CheckResultShape(Entity expr, Type? returnType, Func number switch { - Number.Integer => true, + // An integer beyond the range of int or long is not held by it: converting it there wrapped it, as + // 2^32 over int was 0. https://github.com/asc-community/AngouriMath/issues/2720 + Number.Integer { EInteger: var integer } => type == typeof(int) ? integer.CanFitInInt32() + : type == typeof(long) ? integer.CanFitInInt64() : true, Number.Real => type == typeof(double) || type == typeof(float) || type == typeof(System.Numerics.Complex), _ => type == typeof(System.Numerics.Complex), }; @@ -249,6 +252,14 @@ IBinaryNode twoArg var other => protocol.ConvertOtherNode(other.DirectChildren.Select(c => BuildTree(c, cachedSubexpressions, variableAssignments, newLocalVars, protocol, constantType)), expr) }; + // An integer beyond long stays a constant, so that where it meets a double it is converted once, as it is + // compiled, rather than on every call; and so does a number beside matrix arguments, so that a matrix of + // whole numbers can tell it from an argument (TensorCompilation.WidenedBeside). + // https://github.com/asc-community/AngouriMath/issues/2720 + if (subTree is ConstantExpression { Value: System.Numerics.BigInteger } + || constantType is not null && expr is Number && subTree is ConstantExpression) + return subTree; + var newVar = Expression.Variable(subTree.Type); variableAssignments.Add(Expression.Assign(newVar, subTree)); cachedSubexpressions[expr] = newVar; diff --git a/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.Elementwise.cs b/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.Elementwise.cs index 3e4f6dd39..b7202585d 100644 --- a/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.Elementwise.cs +++ b/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.Elementwise.cs @@ -53,7 +53,8 @@ private MapKit(MethodInfo map, MethodInfo zip, Func mapKits = new[] { @@ -72,6 +73,9 @@ private MapKit(MethodInfo map, MethodInfo zip, Func(), MapKit.For(), MapKit.For(), + MapKit.For(), + MapKit.For(), + MapKit.For(), }.ToDictionary(pair => pair.Key, pair => pair.Value); /// The closed methods for a vector, a one-dimensional array, of one element type. @@ -313,24 +317,40 @@ internal static (Expression Left, Expression Right) Widened(Expression left, Exp if (!IsTensor(left.Type) || !IsTensor(right.Type) || left.Type == right.Type) return (left, right); var (a, b) = (ElementOf(left.Type), ElementOf(right.Type)); - if (mapKits.ContainsKey((a, b))) + if (mapKits.ContainsKey((a, b)) && !AreWholeNumbers(a, b)) return (Widen(left, b, convert), right); - if (mapKits.ContainsKey((b, a))) + if (mapKits.ContainsKey((b, a)) && !AreWholeNumbers(a, b)) return (left, Widen(right, a, convert)); return (left, right); } + private static bool AreWholeNumbers(Type a, Type b) + => IsWhole(a) && IsWhole(b); + + private static bool IsWhole(Type type) + => type == typeof(int) || type == typeof(long) || type == typeof(BigInteger); + /// /// A matrix beside a number of a wider type, widened to that type, as widens the narrower of /// two matrices. The number was converted to the entries' type instead, which truncated it: over a double /// x and a matrix argument A over long, det(x * A) was 0 at x = 0.5, and a complex /// number beside a matrix over double was refused. Unchanged where the number is not wider than the entries. /// https://github.com/asc-community/AngouriMath/issues/105 + /// + /// A matrix of whole numbers is widened to a wider whole number only beside a constant, which is known not to + /// fit the entries: over int, 2^32 was converted to int and wrapped to 0, and over long, 10^20 threw. Beside a + /// long argument a matrix of int keeps its type, so that a compile asking for int[,] still answers. + /// https://github.com/asc-community/AngouriMath/issues/2720 + /// /// - internal static Expression WidenedBeside(Expression tensor, Type number, Func convert) + internal static Expression WidenedBeside(Expression tensor, Expression number, Func convert) { var element = ElementOf(tensor.Type); - return element != number && mapKits.ContainsKey((element, number)) ? Widen(tensor, number, convert) : tensor; + if (element == number.Type || !mapKits.ContainsKey((element, number.Type))) + return tensor; + if (AreWholeNumbers(element, number.Type) && number is not ConstantExpression) + return tensor; + return Widen(tensor, number.Type, convert); } private static Expression Widen(Expression tensor, Type to, Func convert) diff --git a/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs b/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs index a7c01c0bb..afdd01e64 100644 --- a/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs +++ b/Sources/AngouriMath/Functions/Compilation/IntoLinq/TensorCompilation.cs @@ -835,7 +835,7 @@ internal static Expression Build(Entity.Matrix matrix, IReadOnlyList { if (node is Entity.Powf) return Expression.Call(leftKit!.Power, left, Exponent(right, convert)); - left = WidenedBeside(left, right.Type, convert); + left = WidenedBeside(left, right, convert); leftKit = kitsByTensor[left.Type]; var scalar = convert(right, ElementOf(left.Type)); return node switch @@ -847,7 +847,7 @@ internal static Expression Build(Entity.Matrix matrix, IReadOnlyList _ => null, }; } - right = WidenedBeside(right, left.Type, convert); + right = WidenedBeside(right, left, convert); rightKit = kitsByTensor[right.Type]; var value = convert(left, ElementOf(right.Type)); return node switch diff --git a/Sources/Tests/UnitTests/Common/ACompiledIntegerBeyondLongTest.cs b/Sources/Tests/UnitTests/Common/ACompiledIntegerBeyondLongTest.cs new file mode 100644 index 000000000..e47923506 --- /dev/null +++ b/Sources/Tests/UnitTests/Common/ACompiledIntegerBeyondLongTest.cs @@ -0,0 +1,84 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System.Numerics; +using AngouriMath.Extensions; +using Xunit; +using Complex = System.Numerics.Complex; + +namespace AngouriMath.Tests.Common +{ + /// + /// An integer constant of 2^63 or more went through long whatever type was compiled to, and + /// Compile threw . Over double and Complex it is now the nearest + /// double, an infinity beyond their range, as evaluation gives it; over it is exact. + /// https://github.com/asc-community/AngouriMath/issues/2720 + /// + [Trait("Area", "Compilation")] + public sealed class ACompiledIntegerBeyondLongTest + { + // N is replaced by the evaluated constant, so that it reaches the compiler as one number. The values are + // Python's float() of the exact value, which rounds to nearest. + [Theory] + [InlineData("N * x", "10^20", 2, 2e20)] + [InlineData("x + N", "12345678901234567890", 0, 1.2345678901234567e19)] + [InlineData("x / N", "10^20", 2, 2e-20)] + [InlineData("N / x", "10^20", 2, 5e19)] + [InlineData("N * x", "2^63 - 1", 2, 1.8446744073709552e19)] + [InlineData("N * x", "2^63", 2, 1.8446744073709552e19)] + [InlineData("N * x", "2^63 + 1", 2, 1.8446744073709552e19)] + [InlineData("x + N", "-2^63 - 1", 0, -9.223372036854776e18)] + [InlineData("x - N", "2^64 + 1", 0, -1.8446744073709552e19)] + [InlineData("x ^ 2 - N", "2^64", 3, -1.8446744073709552e19)] + [InlineData("N / x", "602214076 * 10^15", 1, 6.02214076e23)] + [InlineData("N * x", "10^400", 2, double.PositiveInfinity)] + [InlineData("x - N", "10^400", 2, double.NegativeInfinity)] + [InlineData("x / N", "10^400", 2, 0.0)] + [InlineData("N * x", "(2^64 + 1) / 3", 3, 1.8446744073709552e19)] + [InlineData("x + N", "(10^400 + 1) / 7", 0, double.PositiveInfinity)] + [InlineData("N * x", "3 / (2^64 + 1)", 1, 1.6263032587282567e-19)] + public void Issue2720_AConstantBeyondLongIsTheDoubleItEvaluatesTo(string shape, string constant, double x, double expected) + { + var f = shape.ToEntity().Substitute("N", constant.ToEntity().Evaled); + var evaluated = (double)(Entity.Number)f.Substitute("x", x).EvalNumerical(); + Assert.Equal(expected, evaluated); + Assert.Equal(expected, f.Compile("x")(x)); + Assert.Equal(new Complex(expected, 0), f.Compile("x")(x)); + Assert.Equal(new Complex(expected, 0), f.Compile("x").Call(x)); + } + + [Theory] + [InlineData("10^20", "100000000000000000001")] + [InlineData("2^64", "18446744073709551617")] + [InlineData("-2^63 - 2", "-9223372036854775809")] + public void Issue2720_AConstantBeyondLongIsExactOverBigInteger(string constant, string sum) + { + var f = "x + N".ToEntity().Substitute("N", constant.ToEntity().Evaled); + Assert.Equal(BigInteger.Parse(sum), f.Compile("x")(1)); + } + + // The runtime's conversion truncated: 2^63 - 1 was 2^63 - 1024 and 2^64 + 2^11 + 1 was 2^64. + [Theory] + [InlineData("9223372036854775807", 9.223372036854776e18)] + [InlineData("-9223372036854775809", -9.223372036854776e18)] + [InlineData("18446744073709553665", 1.8446744073709556e19)] + [InlineData("1" + "0000000000" + "0000000000" + "0000000000" + "0000000000", 1e40)] + public void Issue2720_ABigIntegerArgumentIsTheNearestDouble(string argument, double expected) + { + var value = BigInteger.Parse(argument); + Assert.Equal(expected, "x".ToEntity().Compile("x")(value)); + Assert.Equal(new Complex(expected, 0), "x".ToEntity().Compile("x")(value)); + } + + [Fact] + public void Issue2720_AConstantBeyondLongIsADoubleBesideALong() + { + var f = "N * x".ToEntity().Substitute("N", "2^64".ToEntity().Evaled); + Assert.Equal(3.6893488147419103e19, f.Compile("x")(2)); + } + } +} diff --git a/Sources/Tests/UnitTests/Common/CompileMatrixTest.cs b/Sources/Tests/UnitTests/Common/CompileMatrixTest.cs index 6fa4142b9..0870066e8 100644 --- a/Sources/Tests/UnitTests/Common/CompileMatrixTest.cs +++ b/Sources/Tests/UnitTests/Common/CompileMatrixTest.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) 2019-2026 Angouri. // AngouriMath is licensed under MIT. // Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. @@ -84,6 +84,19 @@ public void AnExpressionOfMatricesWithAScalarValueStillCompilesToTheScalar() Assert.Equal(2.0, f(1, 2, 3, 4)); } + // A matrix of int beside a constant past int is a matrix of long, as beside a double it is one of double. The + // constant was converted to int, so 2^32 * A was 0. Beside a long argument it keeps its type, and a compile + // asking for int[,] still answers. https://github.com/asc-community/AngouriMath/issues/2720 + [Fact] + public void AMatrixOfIntBesideAConstantPastIntIsAMatrixOfLong() + { + var a = new int[,] { { 1, 2 }, { 3, 4 } }; + var product = "A * 4294967296".ToEntity().Compile("A")(a); + Assert.Equal(new long[,] { { 4294967296, 8589934592 }, { 12884901888, 17179869184 } }, product); + Assert.Throws(() => "A * 4294967296".ToEntity().Compile("A")); + Assert.Equal(new int[,] { { 3, 6 }, { 9, 12 } }, "A * n".ToEntity().Compile("A", "n")(a, 3)); + } + [Fact] public void ComplexAndIntegerElementsHaveTheirOwnTensors() { @@ -291,6 +304,12 @@ private static void Near(Complex expected, Complex actual, string where) [InlineData("trace(A ^ (-1))")] [InlineData("det(A ^ (-2))")] [InlineData("trace(2 / A + A / 4)")] + // A constant beyond int was wrapped over int, 2^32 to 0, and one beyond long threw OverflowException. + // https://github.com/asc-community/AngouriMath/issues/2720 + [InlineData("trace(A * 4294967296)")] + [InlineData("trace(A) + 2147483648")] + [InlineData("trace(A * 100000000000000000000)")] + [InlineData("det(A) * 18446744073709551616")] public void ANumberOfAMatrixOfWholeNumbersAgreesWithEvaluation(string expression) { var e = expression.ToEntity();