authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-07-26 05:54:30+00:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2020-07-26 05:54:30+00:00
log40d81a8364899626ad787f03d94111cd21b9263d
tree3897fdeb330d6a5c8882363314d7c6e85d509366
parenta36772ee642607326c48a4ddb3acfa600cb502b6
parent46106b018cc5c870648cf26d4e7413e8a60ad1e4
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #5678 from antlilja/float-testing

Add functions for testing floats with margins and epsilons to standard library

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

lib/std/testing.zig+53
......@@ -171,6 +171,59 @@ test "expectEqual.union(enum)" {
171171 expectEqual(a10, a10);
172172}
173173
174/// This function is intended to be used only in tests. When the actual value is not
175/// within the margin of the expected value,
176/// prints diagnostics to stderr to show exactly how they are not equal, then aborts.
177/// The types must be floating point
178pub fn expectWithinMargin(expected: var, actual: @TypeOf(expected), margin: @TypeOf(expected)) void {
179 std.debug.assert(margin >= 0.0);
180
181 switch (@typeInfo(@TypeOf(actual))) {
182 .Float,
183 .ComptimeFloat,
184 => {
185 if (@fabs(expected - actual) > margin) {
186 std.debug.panic("actual {}, not within margin {} of expected {}", .{ actual, margin, expected });
187 }
188 },
189 else => @compileError("Unable to compare non floating point values"),
190 }
191}
192
193test "expectWithinMargin.f32" {
194 const x: f32 = 12.0;
195 const y: f32 = 12.06;
196
197 expectWithinMargin(x, y, 0.1);
198}
199
200/// This function is intended to be used only in tests. When the actual value is not
201/// within the epsilon of the expected value,
202/// prints diagnostics to stderr to show exactly how they are not equal, then aborts.
203/// The types must be floating point
204pub fn expectWithinEpsilon(expected: var, actual: @TypeOf(expected), epsilon: @TypeOf(expected)) void {
205 std.debug.assert(epsilon >= 0.0 and epsilon <= 1.0);
206
207 const margin = epsilon * expected;
208 switch (@typeInfo(@TypeOf(actual))) {
209 .Float,
210 .ComptimeFloat,
211 => {
212 if (@fabs(expected - actual) > margin) {
213 std.debug.panic("actual {}, not within epsilon {}, of expected {}", .{ actual, epsilon, expected });
214 }
215 },
216 else => @compileError("Unable to compare non floating point values"),
217 }
218}
219
220test "expectWithinEpsilon.f32" {
221 const x: f32 = 12.0;
222 const y: f32 = 13.2;
223
224 expectWithinEpsilon(x, y, 0.1);
225}
226
174227/// This function is intended to be used only in tests. When the two slices are not
175228/// equal, prints diagnostics to stderr to show exactly how they are not equal,
176229/// then aborts.