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
27 changes: 27 additions & 0 deletions BREAKING-CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<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`, 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<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 * 4294967296".Compile<int[,], int[,]>("A")` | `[[0, 0], [0, 0]]` | throws `UncompilableNodeException` |
| `"A * 4294967296".Compile<int[,], long[,]>("A")` | throws `UncompilableNodeException` | `[[4294967296, 8589934592], [12884901888, 17179869184]]` |
| `"A * n".Compile<int[,], long, int[,]>("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
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,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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ 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. The last are taken beside a
// constant only (see WidenedBeside).
[ConstantField]
private static readonly Dictionary<(Type From, Type To), MapKit> mapKits = new[]
{
Expand All @@ -72,6 +73,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 Expand Up @@ -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);

/// <summary>
/// A matrix beside a number of a wider type, widened to that type, as <see cref="Widened"/> widens the narrower of
/// two matrices. The number was converted to the entries' type instead, which truncated it: over a double
/// <c>x</c> and a matrix argument <c>A</c> over long, <c>det(x * A)</c> was 0 at <c>x = 0.5</c>, 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
/// <para>
/// 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
/// </para>
/// </summary>
internal static Expression WidenedBeside(Expression tensor, Type number, Func<Expression, Type, Expression> convert)
internal static Expression WidenedBeside(Expression tensor, Expression number, Func<Expression, Type, Expression> 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<Expression, Type, Expression> convert)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -835,7 +835,7 @@ internal static Expression Build(Entity.Matrix matrix, IReadOnlyList<Expression>
{
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
Expand All @@ -847,7 +847,7 @@ internal static Expression Build(Entity.Matrix matrix, IReadOnlyList<Expression>
_ => 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
Expand Down
Loading
Loading