Skip to content

Commit 23b1aad

Browse files
Fix Float#abs to return self (#16655)
This fixes a regression from #15814 which unintentionally changed the return type of `Float32#abs` to `Float64`. Previously, it returned `Float32`. `Math.copysign(self, 1)` falls back to the overload without restrictions which converts both arguments to `Float64` and thus returns `Float64`. This patch fixes that by explicitly targeting the `Math.copysign(Float32, Float32)` overload for `Float32#abs`. `Float64#abs` is not broken, but still applies an unnecessary integer-to-float conversion when we should be using a float right away. I discovered this type mismatch while researching #13389
1 parent 9cf0528 commit 23b1aad

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

src/float.cr

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -227,8 +227,8 @@ struct Float32
227227
(unsafe_as(UInt32) ^ 0x80000000_u32).unsafe_as(Float32)
228228
end
229229

230-
def abs
231-
Math.copysign(self, 1)
230+
def abs : Float32
231+
Math.copysign(self, 1.0_f32)
232232
end
233233

234234
# Returns `-1` if the sign bit of this float is set, `1` otherwise.
@@ -448,8 +448,8 @@ struct Float64
448448
(unsafe_as(UInt64) ^ 0x80000000_00000000_u64).unsafe_as(Float64)
449449
end
450450

451-
def abs
452-
Math.copysign(self, 1)
451+
def abs : Float64
452+
Math.copysign(self, 1.0)
453453
end
454454

455455
# Returns `-1` if the sign bit of this float is set, `1` otherwise.

0 commit comments

Comments
 (0)