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
30 changes: 30 additions & 0 deletions BREAKING-CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,36 @@ 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<TIn, TOut>` 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`. The same holds for a `long` argument: an `int[,]` beside it
is a `long[,]`, so a compile that asks for an `int[,]` result throws `UncompilableNodeException`. It used to convert the
argument to `int`, which was right while the argument fitted and wrapped past it; it now refuses at every value. Ask
for `long[,]`, which used to be refused. Measured on master `2a7247653` and on this branch
([#2720](https://github.com/asc-community/AngouriMath/issues/2720)).

| | Was | Now |
|---|---|---|
| `"100000000000000000000 * x".Compile<double, double>("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<BigInteger, double>("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<int[,], double>("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 * n".Compile<int[,], long, int[,]>("A", "n")` at `[[1, 2], [3, 4]]`, `n = 3` | `[[3, 6], [9, 12]]` | throws `UncompilableNodeException` |
| the same at `n = 4294967296` | `[[0, 0], [0, 0]]` | throws `UncompilableNodeException` |
| `"A * n".Compile<int[,], long, long[,]>("A", "n")` at `n = 4294967296` | throws `UncompilableNodeException` | `[[4294967296, 8589934592], [12884901888, 17179869184]]` |
| `"trace(A * n)".Compile<int[,], long, double>("A", "n")` at `n = 2147483648` | `-2147483648` | `10737418240` |
| `"A * 4294967296".Compile<int[,], int[,]>("A")` | `[[0, 0], [0, 0]]` | throws `UncompilableNodeException` |

### 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
Expand Down
6 changes: 6 additions & 0 deletions Sources/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
36 changes: 36 additions & 0 deletions Sources/AngouriMath/Functions/Compilation/BigIntegerConversions.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// A <see cref="BigInteger"/> as the nearest <see cref="double"/>, <see cref="float"/> or
/// <see cref="System.Numerics.Complex"/>, 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
/// </summary>
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));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -472,10 +472,17 @@ private Expression HandlePiecewise(IEnumerable<Expression> 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)
Expand Down Expand Up @@ -524,7 +531,9 @@ private static MethodInfo GetDef(string name, int argCount, Type type)
{ (typeof(long), typeof(System.Numerics.Complex)), Conv<long, System.Numerics.Complex>(v => (System.Numerics.Complex)v) },
{ (typeof(float), typeof(System.Numerics.Complex)), Conv<float, System.Numerics.Complex>(v => (System.Numerics.Complex)v) },
{ (typeof(double), typeof(System.Numerics.Complex)), Conv<double, System.Numerics.Complex>(v => (System.Numerics.Complex)v) },
{ (typeof(BigInteger), typeof(System.Numerics.Complex)), Conv<BigInteger, System.Numerics.Complex>(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<BigInteger, System.Numerics.Complex>(v => BigIntegerConversions.ToComplex(v)) },

{ (typeof(int), typeof(BigInteger)), Conv<int, BigInteger>(v => (BigInteger)v) },
{ (typeof(long), typeof(BigInteger)), Conv<long, BigInteger>(v => (BigInteger)v) },
Expand All @@ -533,8 +542,8 @@ private static MethodInfo GetDef(string name, int argCount, Type type)

{ (typeof(BigInteger), typeof(int)), Conv<BigInteger, int>(v => (int)v) },
{ (typeof(BigInteger), typeof(long)), Conv<BigInteger, long>(v => (long)v) },
{ (typeof(BigInteger), typeof(float)), Conv<BigInteger, float>(v => (float)v) },
{ (typeof(BigInteger), typeof(double)), Conv<BigInteger, double>(v => (double)v) },
{ (typeof(BigInteger), typeof(float)), Through<BigInteger, float>(v => BigIntegerConversions.ToSingle(v)) },
{ (typeof(BigInteger), typeof(double)), Through<BigInteger, double>(v => BigIntegerConversions.ToDouble(v)) },
};

/// <summary>
Expand All @@ -559,6 +568,9 @@ private static MethodInfo GetDef(string name, int argCount, Type type)
private static MethodInfo Named<T>(Expression<Func<T, bool>> e)
=> ((MethodCallExpression)e.Body).Method;

private static MethodInfo Through<TFrom, TTo>(Expression<Func<TFrom, TTo>> e)
=> ((MethodCallExpression)e.Body).Method;

private static MethodInfo Conv<TFrom, TTo>(Expression<Func<TFrom, TTo>> e)
=> ((UnaryExpression)e.Body).Method
?? throw new AngouriBugException($"{typeof(TFrom)} -> {typeof(TTo)} is not a user-defined conversion");
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,10 @@ private static void CheckResultShape(Entity expr, Type? returnType, Func<Variabl
private static bool Holds(Type type, Number number)
=> 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),
};
Expand Down Expand Up @@ -249,6 +252,11 @@ 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. https://github.com/asc-community/AngouriMath/issues/2720
if (subTree is ConstantExpression { Value: System.Numerics.BigInteger })
return subTree;

var newVar = Expression.Variable(subTree.Type);
variableAssignments.Add(Expression.Assign(newVar, subTree));
cachedSubexpressions[expr] = newVar;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ private MapKit(MethodInfo map, MethodInfo zip, Func<Expression, ParameterExpress
}

// Each element type onto itself, and the widenings a number takes: onto double from the narrower real types,
// and onto Complex from every real one.
// onto Complex from every real one, and among the whole numbers onto the wider. A matrix over int beside an
// integer past int had it wrapped, 2^32 to 0, and one over long beside an integer past long threw.
// https://github.com/asc-community/AngouriMath/issues/2720
[ConstantField]
private static readonly Dictionary<(Type From, Type To), MapKit> mapKits = new[]
{
Expand All @@ -72,6 +74,9 @@ private MapKit(MethodInfo map, MethodInfo zip, Func<Expression, ParameterExpress
MapKit.For<int, Int32Operations, Complex, ComplexOperations>(),
MapKit.For<long, Int64Operations, Complex, ComplexOperations>(),
MapKit.For<BigInteger, BigIntegerOperations, Complex, ComplexOperations>(),
MapKit.For<int, Int32Operations, long, Int64Operations>(),
MapKit.For<int, Int32Operations, BigInteger, BigIntegerOperations>(),
MapKit.For<long, Int64Operations, BigInteger, BigIntegerOperations>(),
}.ToDictionary(pair => pair.Key, pair => pair.Value);

/// <summary>The closed methods for a vector, a one-dimensional array, of one element type.</summary>
Expand Down
84 changes: 84 additions & 0 deletions Sources/Tests/UnitTests/Common/ACompiledIntegerBeyondLongTest.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// An integer constant of 2^63 or more went through <c>long</c> whatever type was compiled to, and
/// <c>Compile</c> threw <see cref="System.OverflowException"/>. Over double and Complex it is now the nearest
/// double, an infinity beyond their range, as evaluation gives it; over <see cref="BigInteger"/> it is exact.
/// https://github.com/asc-community/AngouriMath/issues/2720
/// </summary>
[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<double, double>("x")(x));
Assert.Equal(new Complex(expected, 0), f.Compile<Complex, Complex>("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<BigInteger, BigInteger>("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<BigInteger, double>("x")(value));
Assert.Equal(new Complex(expected, 0), "x".ToEntity().Compile<BigInteger, Complex>("x")(value));
}

[Fact]
public void Issue2720_AConstantBeyondLongIsADoubleBesideALong()
{
var f = "N * x".ToEntity().Substitute("N", "2^64".ToEntity().Evaled);
Assert.Equal(3.6893488147419103e19, f.Compile<long, double>("x")(2));
}
}
}
21 changes: 20 additions & 1 deletion Sources/Tests/UnitTests/Common/CompileMatrixTest.cs
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -84,6 +84,19 @@ public void AnExpressionOfMatricesWithAScalarValueStillCompilesToTheScalar()
Assert.Equal(2.0, f(1, 2, 3, 4));
}

// A matrix of int beside a long is a matrix of long, as beside a double it is one of double. The long was
// converted to int, so 2^32 * A was 0. https://github.com/asc-community/AngouriMath/issues/2720
[Fact]
public void AMatrixOfIntBesideALongIsAMatrixOfLong()
{
var a = new int[,] { { 1, 2 }, { 3, 4 } };
var product = "A * n".ToEntity().Compile<int[,], long, long[,]>("A", "n")(a, 4294967296);
Assert.Equal(new long[,] { { 4294967296, 8589934592 }, { 12884901888, 17179869184 } }, product);
Assert.Equal(10737418240.0, "trace(A * n)".ToEntity().Compile<int[,], long, double>("A", "n")(a, 2147483648));
Assert.Throws<UncompilableNodeException>(() => "A * n".ToEntity().Compile<int[,], long, int[,]>("A", "n"));
Assert.Throws<UncompilableNodeException>(() => "A * 4294967296".ToEntity().Compile<int[,], int[,]>("A"));
}

[Fact]
public void ComplexAndIntegerElementsHaveTheirOwnTensors()
{
Expand Down Expand Up @@ -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();
Expand Down
Loading