authorgravatar for info@bnoordhuis.nlBen Noordhuis <info@bnoordhuis.nl> 2018-06-30 01:44:54+02:00
committergravatar for info@bnoordhuis.nlBen Noordhuis <info@bnoordhuis.nl> 2018-06-30 01:58:17+02:00
logd293f1a0edf0e2e42f03ad416c7f5d649776ae88
treee998948e3239f07e06fd4c2f0ab2793d573f7c0d
parent1abc9252922f242b801fe88533b482a18724237d

add std.math f16 floor support

refs #1122

2 files changed, 55 insertions(+), 0 deletions(-)

std/math/floor.zig+50
......@@ -12,12 +12,47 @@ const math = std.math;
1212pub fn floor(x: var) @typeOf(x) {
1313 const T = @typeOf(x);
1414 return switch (T) {
15 f16 => floor16(x),
1516 f32 => floor32(x),
1617 f64 => floor64(x),
1718 else => @compileError("floor not implemented for " ++ @typeName(T)),
1819 };
1920}
2021
22fn floor16(x: f16) f16 {
23 var u = @bitCast(u16, x);
24 const e = @intCast(i16, (u >> 10) & 31) - 15;
25 var m: u16 = undefined;
26
27 // TODO: Shouldn't need this explicit check.
28 if (x == 0.0) {
29 return x;
30 }
31
32 if (e >= 10) {
33 return x;
34 }
35
36 if (e >= 0) {
37 m = u16(1023) >> @intCast(u4, e);
38 if (u & m == 0) {
39 return x;
40 }
41 math.forceEval(x + 0x1.0p120);
42 if (u >> 15 != 0) {
43 u += m;
44 }
45 return @bitCast(f16, u & ~m);
46 } else {
47 math.forceEval(x + 0x1.0p120);
48 if (u >> 15 == 0) {
49 return 0.0;
50 } else {
51 return -1.0;
52 }
53 }
54}
55
2156fn floor32(x: f32) f32 {
2257 var u = @bitCast(u32, x);
2358 const e = @intCast(i32, (u >> 23) & 0xFF) - 0x7F;
......@@ -84,10 +119,17 @@ fn floor64(x: f64) f64 {
84119}
85120
86121test "math.floor" {
122 assert(floor(f16(1.3)) == floor16(1.3));
87123 assert(floor(f32(1.3)) == floor32(1.3));
88124 assert(floor(f64(1.3)) == floor64(1.3));
89125}
90126
127test "math.floor16" {
128 assert(floor16(1.3) == 1.0);
129 assert(floor16(-1.3) == -2.0);
130 assert(floor16(0.2) == 0.0);
131}
132
91133test "math.floor32" {
92134 assert(floor32(1.3) == 1.0);
93135 assert(floor32(-1.3) == -2.0);
......@@ -100,6 +142,14 @@ test "math.floor64" {
100142 assert(floor64(0.2) == 0.0);
101143}
102144
145test "math.floor16.special" {
146 assert(floor16(0.0) == 0.0);
147 assert(floor16(-0.0) == -0.0);
148 assert(math.isPositiveInf(floor16(math.inf(f16))));
149 assert(math.isNegativeInf(floor16(-math.inf(f16))));
150 assert(math.isNan(floor16(math.nan(f16))));
151}
152
103153test "math.floor32.special" {
104154 assert(floor32(0.0) == 0.0);
105155 assert(floor32(-0.0) == -0.0);
std/math/index.zig+5
......@@ -56,6 +56,11 @@ pub fn approxEq(comptime T: type, x: T, y: T, epsilon: T) bool {
5656pub fn forceEval(value: var) void {
5757 const T = @typeOf(value);
5858 switch (T) {
59 f16 => {
60 var x: f16 = undefined;
61 const p = @ptrCast(*volatile f16, &x);
62 p.* = x;
63 },
5964 f32 => {
6065 var x: f32 = undefined;
6166 const p = @ptrCast(*volatile f32, &x);