Skip to content

Commit

Permalink
Update Rational.cs
Browse files Browse the repository at this point in the history
- Dividing rational numbers by zero now returns NaN
- Fix how NaN, positive infinity, and negative infinity are displayed
- Other minor changes
  • Loading branch information
HamletTanyavong committed Nov 6, 2023
1 parent 92d6193 commit f87f049
Showing 1 changed file with 56 additions and 2 deletions.
58 changes: 56 additions & 2 deletions src/Mathematics.NET/Core/Rational.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ public Rational(T p, T q)

public static Rational<T> operator /(Rational<T> x, Rational<T> y)
{
if (y._denominator == T.Zero)
if (y._numerator == T.Zero)
{
return NaN;
}
Expand Down Expand Up @@ -248,6 +248,21 @@ public int CompareTo(Rational<T> 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;

Expand All @@ -271,6 +286,45 @@ public string ToString(string? format, IFormatProvider? provider)

public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> 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;

Expand All @@ -288,8 +342,8 @@ public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan
return false;
}

charsWritten = 1;
destination[0] = '0';
charsWritten = 1;
return true;
}

Expand Down

0 comments on commit f87f049

Please sign in to comment.