比较自定义浮点结构

问题描述 投票:0回答:1

我做了一个结构

BigValue
具有
decimal Significand
int Exponent
Significand
始终标准化为 1 个整数位。我已经编写了方法来比较此类结构(由它表示的数字),但我不确定我是否错过了某些东西,或者也许我以非常次优的方式做到了这一点?
IsPositive
是布尔标志,当
true
时为
Significand >= 0
。 完整结构以防万一:https://pastebin.com/ndrsR2in

    public int CompareTo(BigValue other)
    {
        if (Significand == 0)
            return other.Significand == 0 
                ? 0 
                : other.IsPositive ? -1 : 1;

        if (other.Significand == 0) return IsPositive ? 1 : -1;

        if (IsPositive != other.IsPositive) return IsPositive ? 1 : -1;

        var exponentCompare = Exponent.CompareTo(other.Exponent);
        if (exponentCompare == 0)
            return Significand.CompareTo(other.Significand);
        
        return IsPositive
            ? exponentCompare
            : exponentCompare * -1;
    }
c# math floating-point compareto
1个回答
0
投票

删除了对 Significand == 0 的检查,因为它已在后续比较中涵盖。 简化了 exponentCompare 行以提高可读性。 更改了负指数的返回语句以使用 -exponentCompare 来保持一致性。

© www.soinside.com 2019 - 2024. All rights reserved.