Skip to content

Commit 76748bc

Browse files
committed
Add support for relative and absolute errors in comparing floats
1 parent a687c3a commit 76748bc

File tree

3 files changed

+65
-1
lines changed

3 files changed

+65
-1
lines changed

test/test-float-equality.4th

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
\ Copyright 2023 nomennescio
2+
3+
\ pass
4+
<{ 1e -> 1e }>
5+
\ fail
6+
<{ 1.001e -> 1e }>
7+
8+
\ abs<> ( f1 f2 -- ? ) := |f1-f2| > epsilon
9+
F<>: abs<>
10+
0.01e epsilon f!
11+
\ pass
12+
<{ 1.001e -> 1e }>
13+
\ fail
14+
<{ 1.1e -> 1e }>
15+
1e epsilon f!
16+
\ pass
17+
<{ 1.1e -> 1e }>
18+
19+
\ rel<> ( f1 f2 -- ? ) := |f1-f2|/|f1+f2| > epsilon
20+
F<>: rel<>
21+
0.05e epsilon f!
22+
\ pass
23+
<{ 5.5e -> 5e }>
24+
<{ 11e -> 10e }>
25+
\ fail
26+
<{ 5.6e -> 5e }>
27+
<{ 11.2e -> 10e }>
28+
29+
\ f<> ( f1 f2 -- ? ) := f1 <> f2
30+
F<>: f<>
31+
\ pass
32+
<{ 1e -> 1e }>
33+
\ fail
34+
<{ 1.001e -> 1e }>

test/test-float-equality.expected

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
<PASSED::>Test Passed
3+
4+
<FAILED::>Expected 1. , got 1.001
5+
6+
<PASSED::>Test Passed
7+
8+
<FAILED::>Expected 1. , got 1.1
9+
10+
<PASSED::>Test Passed
11+
12+
<PASSED::>Test Passed
13+
14+
<PASSED::>Test Passed
15+
16+
<FAILED::>Expected 5. , got 5.6
17+
18+
<FAILED::>Expected 10. , got 11.2
19+
20+
<PASSED::>Test Passed
21+
22+
<FAILED::>Expected 1. , got 1.001

testest.4th

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,16 @@ variable ^#results.f ' #results.f$ ^#results.f !
7070

7171
: -> depth start-depth @ - dup #actuals ! actuals[] fdepth start-fdepth @ - dup #actuals.f ! actuals.f[] store-stacks ;
7272

73+
variable ^f<>
74+
: F<>: ' ^f<> ! ;
75+
F<>: f<>
76+
77+
fvariable epsilon
78+
: rel<> epsilon f@ f~rel 0= ;
79+
: abs<> epsilon f@ f~abs 0= ;
80+
7381
: compare { e* a* d -- d' } e* @ a* @ <> d + ;
74-
: compare.f { e* a* d -- d' } e* f@ a* f@ f<> d + ;
82+
: compare.f { e* a* d -- d' } e* f@ a* f@ ^f<> @ ^ d + ;
7583

7684
: compare-results { #e e* #a a* s 'cmp } ( #p #f #r -- #p' #f' #r' )
7785
#e #a = if

0 commit comments

Comments
 (0)