authorgravatar for liljaanton2001@gmail.comantlilja <liljaanton2001@gmail.com> 2020-06-23 18:08:15+02:00
committergravatar for liljaanton2001@gmail.comantlilja <liljaanton2001@gmail.com> 2020-06-23 18:08:15+02:00
log46106b018cc5c870648cf26d4e7413e8a60ad1e4
treecb66fae6934fc49741c3e4f490839895e7769c79
parent2fc2355fc3d72cbf1ffdc982a42090ada901d21f

Add expectWithinEpsilon + test


1 files changed, 27 insertions(+), 0 deletions(-)

lib/std/testing.zig+27
......@@ -194,6 +194,33 @@ test "expectWithinMargin.f32" {
194194 expectWithinMargin(x, y, 0.1);
195195}
196196
197/// This function is intended to be used only in tests. When the actual value is not
198/// within the epsilon of the expected value,
199/// prints diagnostics to stderr to show exactly how they are not equal, then aborts.
200/// The types must be floating point
201pub fn expectWithinEpsilon(expected: var, actual: @TypeOf(expected), epsilon: @TypeOf(expected)) void {
202 std.debug.assert(epsilon >= 0.0 and epsilon <= 1.0);
203
204 const margin = epsilon * expected;
205 switch (@typeInfo(@TypeOf(actual))) {
206 .Float,
207 .ComptimeFloat,
208 => {
209 if (@fabs(expected - actual) > margin) {
210 std.debug.panic("actual {}, not within epsilon {}, of expected {}", .{ actual, epsilon, expected });
211 }
212 },
213 else => @compileError("Unable to compare non floating point values"),
214 }
215}
216
217test "expectWithinEpsilon.f32" {
218 const x: f32 = 12.0;
219 const y: f32 = 13.2;
220
221 expectWithinEpsilon(x, y, 0.1);
222}
223
197224/// This function is intended to be used only in tests. When the two slices are not
198225/// equal, prints diagnostics to stderr to show exactly how they are not equal,
199226/// then aborts.