From f87f049a05c005ef6a07d96f40fd08688e43ea58 Mon Sep 17 00:00:00 2001 From: Hamlet Tanyavong <34531738+HamletTanyavong@users.noreply.github.com> Date: Mon, 6 Nov 2023 15:33:57 -0600 Subject: [PATCH] Update Rational.cs - Dividing rational numbers by zero now returns NaN - Fix how NaN, positive infinity, and negative infinity are displayed - Other minor changes --- src/Mathematics.NET/Core/Rational.cs | 58 +++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/src/Mathematics.NET/Core/Rational.cs b/src/Mathematics.NET/Core/Rational.cs index ebe22264..0f7bfa6a 100644 --- a/src/Mathematics.NET/Core/Rational.cs +++ b/src/Mathematics.NET/Core/Rational.cs @@ -140,7 +140,7 @@ public Rational(T p, T q) public static Rational operator /(Rational x, Rational y) { - if (y._denominator == T.Zero) + if (y._numerator == T.Zero) { return NaN; } @@ -248,6 +248,21 @@ public int CompareTo(Rational value) public string ToString(string? format, IFormatProvider? provider) { + if (IsNaN(this)) + { + return "NaN"; + } + + if (IsPositiveInfinity(this)) + { + return "∞"; + } + + if (IsNegativeInfinity(this)) + { + return "-∞"; + } + format = string.IsNullOrEmpty(format) ? "MINIMAL" : format.ToUpperInvariant(); provider ??= NumberFormatInfo.InvariantInfo; @@ -271,6 +286,45 @@ public string ToString(string? format, IFormatProvider? provider) public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider? provider) { + if (IsNaN(this)) + { + if (destination.Length < 3) + { + charsWritten = 0; + return false; + } + + "NaN".CopyTo(destination); + charsWritten = 3; + return true; + } + + if (IsPositiveInfinity(this)) + { + if (destination.Length < 1) + { + charsWritten = 0; + return false; + } + + destination[0] = '∞'; + charsWritten = 1; + return true; + } + + if (IsNegativeInfinity(this)) + { + if (destination.Length < 2) + { + charsWritten = 0; + return false; + } + + "-∞".CopyTo(destination); + charsWritten = 2; + return true; + } + format = format.IsEmpty ? "MINIMAL" : format.ToString().ToUpperInvariant(); provider ??= NumberFormatInfo.InvariantInfo; @@ -288,8 +342,8 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan return false; } - charsWritten = 1; destination[0] = '0'; + charsWritten = 1; return true; }