Skip to content

Commit fe00f9d

Browse files
author
Ash Pook
committed
Updated fixed point negation function to avoid branching.
1 parent b346e17 commit fe00f9d

File tree

3 files changed

+12
-9
lines changed

3 files changed

+12
-9
lines changed

source/abacus/gen/main/Fixed.X.t4

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -156,9 +156,10 @@
156156
}
157157

158158
public static void Negate (ref <#= ftd.TypeName #> f, out <#= ftd.TypeName #> result) {
159-
result.numerator = (f.numerator == <#= ftd.RawTypeName #>.MinValue)
160-
? <#= ftd.RawTypeName #>.MaxValue // overflow case
161-
: -f.numerator;
159+
<#= ftd.RawTypeName #> s = f.numerator >> (<#= ftd.BitCount #> - 1); // sign of argument
160+
result.numerator = -f.numerator;
161+
<#= ftd.RawTypeName #> sr = result.numerator >> (<#= ftd.BitCount #> - 1); // sign of result
162+
result.numerator = (result.numerator & ~(sr & s)) | ((sr & s) & <#= ftd.RawTypeName #>.MaxValue);
162163
}
163164

164165
public static void Sqrt (ref <#= ftd.TypeName #> f, out <#= ftd.TypeName #> result) {

source/abacus/src/main/Abacus.Fixed32.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -210,9 +210,10 @@ public static void Modulo (ref Fixed32 a, ref Fixed32 b, out Fixed32 result) {
210210
}
211211

212212
public static void Negate (ref Fixed32 f, out Fixed32 result) {
213-
result.numerator = (f.numerator == Int32.MinValue)
214-
? Int32.MaxValue // overflow case
215-
: -f.numerator;
213+
Int32 s = f.numerator >> (32 - 1); // sign of argument
214+
result.numerator = -f.numerator;
215+
Int32 sr = result.numerator >> (32 - 1); // sign of result
216+
result.numerator = (result.numerator & ~(sr & s)) | ((sr & s) & Int32.MaxValue);
216217
}
217218

218219
public static void Sqrt (ref Fixed32 f, out Fixed32 result) {

source/abacus/src/main/Abacus.Fixed64.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -211,9 +211,10 @@ public static void Modulo (ref Fixed64 a, ref Fixed64 b, out Fixed64 result) {
211211
}
212212

213213
public static void Negate (ref Fixed64 f, out Fixed64 result) {
214-
result.numerator = (f.numerator == Int64.MinValue)
215-
? Int64.MaxValue // overflow case
216-
: -f.numerator;
214+
Int64 s = f.numerator >> (64 - 1); // sign of argument
215+
result.numerator = -f.numerator;
216+
Int64 sr = result.numerator >> (64 - 1); // sign of result
217+
result.numerator = (result.numerator & ~(sr & s)) | ((sr & s) & Int64.MaxValue);
217218
}
218219

219220
public static void Sqrt (ref Fixed64 f, out Fixed64 result) {

0 commit comments

Comments
 (0)