| 1 | const std = @import("../std.zig"); |
| 2 | const math = std.math; |
| 3 | const expect = std.testing.expect; |
| 4 | |
| 5 | /// Returns a value with the magnitude of `magnitude` and the sign of `sign`. |
| 6 | pub fn copysign(magnitude: anytype, sign: @TypeOf(magnitude)) @TypeOf(magnitude) { |
| 7 | const T = @TypeOf(magnitude); |
| 8 | const TBits = @Int(.unsigned, @typeInfo(T).float.bits); |
| 9 | const sign_bit_mask = @as(TBits, 1) << (@bitSizeOf(T) - 1); |
| 10 | const mag = @as(TBits, @bitCast(magnitude)) & ~sign_bit_mask; |
| 11 | const sgn = @as(TBits, @bitCast(sign)) & sign_bit_mask; |
| 12 | return @as(T, @bitCast(mag | sgn)); |
| 13 | } |
| 14 | |
| 15 | test copysign { |
| 16 | inline for ([_]type{ f16, f32, f64, f80, f128 }) |T| { |
| 17 | try expect(copysign(@as(T, 1.0), @as(T, 1.0)) == 1.0); |
| 18 | try expect(copysign(@as(T, 2.0), @as(T, -2.0)) == -2.0); |
| 19 | try expect(copysign(@as(T, -3.0), @as(T, 3.0)) == 3.0); |
| 20 | try expect(copysign(@as(T, -4.0), @as(T, -4.0)) == -4.0); |
| 21 | try expect(copysign(@as(T, 5.0), @as(T, -500.0)) == -5.0); |
| 22 | try expect(copysign(math.inf(T), @as(T, -0.0)) == -math.inf(T)); |
| 23 | try expect(copysign(@as(T, 6.0), -math.nan(T)) == -6.0); |
| 24 | } |
| 25 | } |