From cdc8ca342804a9733c1fe2b93ba9eb3a3d9467c9 Mon Sep 17 00:00:00 2001 From: Desmond Kirkpatrick Date: Wed, 6 Nov 2024 18:55:07 -0800 Subject: [PATCH] Fpvaluecompare (#131) * fp comparison fix for negative, +0 -0 --- .../floating_point_value.dart | 16 +++++++------- .../floating_point_value_test.dart | 21 +++++++++++++++++++ 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/lib/src/arithmetic/floating_point/floating_point_values/floating_point_value.dart b/lib/src/arithmetic/floating_point/floating_point_values/floating_point_value.dart index 83c8d9e1..825758b3 100644 --- a/lib/src/arithmetic/floating_point/floating_point_values/floating_point_value.dart +++ b/lib/src/arithmetic/floating_point/floating_point_values/floating_point_value.dart @@ -552,20 +552,18 @@ class FloatingPointValue implements Comparable { (mantissa.width != other.mantissa.width)) { throw Exception('FloatingPointValue widths must match for comparison'); } - // } else { + final signCompare = sign.compareTo(other.sign); final expCompare = exponent.compareTo(other.exponent); final mantCompare = mantissa.compareTo(other.mantissa); + if ((signCompare != 0) && !(exponent.isZero && mantissa.isZero)) { + return signCompare; + } if (expCompare != 0) { - return expCompare; + return sign.isZero ? expCompare : -expCompare; } else if (mantCompare != 0) { - return mantCompare; - } else { - final signCompare = sign.compareTo(other.sign); - if ((signCompare != 0) && !(exponent.isZero && mantissa.isZero)) { - return signCompare; - } - return 0; + return sign.isZero ? mantCompare : -mantCompare; } + return 0; } /// Return the bias of this FP format diff --git a/test/arithmetic/floating_point/floating_point_value_test.dart b/test/arithmetic/floating_point/floating_point_value_test.dart index e98aa25c..36933ce8 100644 --- a/test/arithmetic/floating_point/floating_point_value_test.dart +++ b/test/arithmetic/floating_point/floating_point_value_test.dart @@ -292,4 +292,25 @@ void main() { final fp2 = FloatingPoint16Value.ofSpacedBinaryString(s); expect(fp, equals(fp2)); }); + + test('Initializing derived type', () { + final fp = FloatingPoint16Value.ofInts(15, 0); + final s = fp.toString(); + final fp2 = FloatingPoint16Value.ofSpacedBinaryString(s); + expect(fp, equals(fp2)); + }); + test('FPV Value comparison', () { + final fp = FloatingPointValue.ofSpacedBinaryString('1 0101 0101'); + expect(fp.compareTo(FloatingPointValue.ofSpacedBinaryString('1 0101 0101')), + 0); + expect(fp.compareTo(FloatingPointValue.ofSpacedBinaryString('1 0100 0101')), + lessThan(0)); + expect(fp.compareTo(FloatingPointValue.ofSpacedBinaryString('1 0101 0100')), + lessThan(0)); + + final fp2 = FloatingPointValue.ofSpacedBinaryString('1 0000 0000'); + expect( + fp2.compareTo(FloatingPointValue.ofSpacedBinaryString('0 0000 0000')), + equals(0)); + }); }