Approximate equality: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(added ReScript)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(18 intermediate revisions by 6 users not shown)
Line 34:
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
Line 81:
end Main;
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 96:
=={{header|ALGOL 68}}==
{{Trans|Kotlin}}
<langsyntaxhighlight lang="algol68">BEGIN # test REAL values for approximate equality #
# returns TRUE if value is approximately equal to other, FALSE otherwide #
PROC approx equals = ( REAL value, REAL other, REAL epsilon )BOOL: ABS ( value - other ) < epsilon;
Line 114:
test( - sqrt( 2 ) * sqrt( 2 ), -2.0 );
test( 3.14159265358979323846, 3.14159265358979324 )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 128:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f APPROXIMATE_EQUALITY.AWK
# converted from C#
Line 152:
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 169:
=={{header|C}}==
{{trans|Java}}
<langsyntaxhighlight lang="c">#include <math.h>
#include <stdbool.h>
#include <stdio.h>
Line 192:
test(3.14159265358979323846, 3.14159265358979324);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>100000000000000.015625, 100000000000000.015625 => 1
Line 204:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
public static class Program
Line 225:
 
public static bool ApproxEquals(this double value, double other, double epsilon) => Math.Abs(value - other) < epsilon;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 239:
=={{header|C++}}==
{{trans|C}}
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <cmath>
Line 266:
test(3.14159265358979323846, 3.14159265358979324);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>100000000000000.015625, 100000000000000.015625 => 1
Line 280:
This solution compares the normalized (i.e. between 0.5 and 1 on implementations which use binary floating point) significands of the floating point numbers, correcting each significand by half the difference in the exponents so that the corrected numbers used for comparison have the same difference in order of magnitude as the original numbers and are stable when the order of the arguments is changed. Unlike the metric of comparing the difference to some fraction of the numbers' size, this approach only requires two floating point operations (the subtraction and comparison at the end), and more directly maps to the fundamental issue which leads to the need for floating-point comparisons, i.e. the limited precision of the significand.
 
<langsyntaxhighlight lang="lisp">
(defun approx-equal (float1 float2 &optional (threshold 0.000001))
"Determine whether float1 and float2 are equal; THRESHOLD is the
Line 291:
(cmp2 (float-sign sign2 (scale-float sig2 (floor (- exp2 exp1) 2)))))
(< (abs (- cmp1 cmp2)) threshold)))))
</syntaxhighlight>
</lang>
 
=={{header|D}}==
{{trans|C#}}
<langsyntaxhighlight lang="d">import std.math;
import std.stdio;
 
Line 314:
test(-sqrt(2.0) * sqrt(2.0), -2.0);
test(3.14159265358979323846, 3.14159265358979324);
}</langsyntaxhighlight>
{{out}}
<pre>100000000000000.015620000000000000, 100000000000000.015620000000000000 => true
Line 328:
{{libheader| System.Math}}
The Delphi has a Math.SameValue function for compare, but all float operations use by default Extended (High precision), we need use double cast for every operation, like division, multiply and square tree.
<syntaxhighlight lang="delphi">
<lang Delphi>
program Approximate_Equality;
 
Line 364:
end.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 381:
The <code>~</code> word takes three arguments: the two values to be compared, and an epsilon value representing the allowed distance between the two values. A positive epsilon performs an absolute distance test, an epsilon of zero performs an exact comparison, and a negative epsilon performs a relative distance test (as required by this task).
{{works with|Factor|0.99 development version 2019-07-10}}
<langsyntaxhighlight lang="factor">USING: formatting generalizations kernel math math.functions ;
 
100000000000000.01 100000000000000.011
Line 393:
 
[ 2dup -1e-15 ~ "%+47.30f %+47.30f -1e-15 ~ : %u\n" printf ]
2 8 mnapply</langsyntaxhighlight>
{{out}}
<pre>
Line 411:
f~ ( r1 r2 r3 – flag ) float-ext “f-proximate”
ANS Forth medley for comparing r1 and r2 for equality: r3>0: f~abs; r3=0: bitwise comparison; r3<0:
<langsyntaxhighlight lang="forth">
: test-f~ ( f1 f2 -- )
1e-18 \ epsilon
Line 417:
if ." True" else ." False" then
;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 433:
Compare against the Python function documented at https://www.python.org/dev/peps/pep-0485/#proposed-implementation,
and with the discussion at https://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python#
<langsyntaxhighlight lang="fortran">program main
implicit none
 
Line 474:
end function
 
end program</langsyntaxhighlight>
{{out}}
<pre> 1.000000000000000156E+14 == 1.000000000000000156E+14 ? T
Line 488:
=={{header|FreeBASIC}}==
{{trans|AWK}}
<langsyntaxhighlight lang="freebasic">#include "string.bi"
 
Dim Shared As Double epsilon = 1
Line 512:
eq_approx(3.14159265358979323846, 3.14159265358979324)
 
Sleep</langsyntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn DoublesAreApproxEqual( val1 as double, val2 as double, epsilon as double ) as CFStringRef
CFStringRef result = @"false"
if ( fn fabs( val1 - val2 ) < epsilon ) then result = @"true"
end fn = result
 
void local fn DoIt
long i
double epsilon = 1e-18, values(15)
 
values(0) = 100000000000000.01 : values(1) = 100000000000000.011
values(2) = 100.01 : values(3) = 100.011
values(4) = 10000000000000.001 / 10000.0 : values(5) = 1000000000.0000001000
values(6) = 0.001 : values(7) = 0.0010000001
values(8) = 0.000000000000000000000101 : values(9) = 0.0
values(10) = fn sqrt(2) * fn sqrt(2) : values(11) = 2.0
values(12) = -fn sqrt(2) * fn sqrt(2) : values(13) = -2.0
values(14) = 3.14159265358979323846 : values(15) = 3.14159265358979324
for i = 0 to 14 step 2
print values(i)@", "values(i+1)@" "fn DoublesAreApproxEqual( values(i), values(i+1), epsilon )
next
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
100000000000000, 100000000000000 true
100.01, 100.011 false
1000000000, 1000000000 false
0.001, 0.0010000001 false
1.01e-22, 0 true
2, 2 false
-2, -2 false
3.141592653589793, 3.141592653589793 true
</pre>
 
=={{header|Go}}==
Go's float64 type is limited to 15 or 16 digits of precision. As there are some numbers in this task which have more digits than this I've used big.Float instead.
<langsyntaxhighlight lang="go">package main
 
import (
Line 571 ⟶ 612:
fmt.Printf("% 21.19g %s %- 21.19g\n", pair[0], s, pair[1])
}
}</langsyntaxhighlight>
 
{{out}}
Line 588 ⟶ 629:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">class Approximate {
private static boolean approxEquals(double value, double other, double epsilon) {
return Math.abs(value - other) < epsilon
Line 608 ⟶ 649:
test(3.14159265358979323846, 3.14159265358979324)
}
}</langsyntaxhighlight>
{{out}}
<pre>100000000000000.020000, 100000000000000.020000 => true
Line 620 ⟶ 661:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">class (Num a, Ord a, Eq a) => AlmostEq a where
eps :: a
 
Line 632 ⟶ 673:
instance AlmostEq Integer where eps = 0
instance AlmostEq Double where eps = 1e-14
instance AlmostEq Float where eps = 1e-5</langsyntaxhighlight>
 
Examples
Line 653 ⟶ 694:
Assignment
 
<langsyntaxhighlight lang="haskell">test :: [(Double, Double)]
test = [(100000000000000.01, 100000000000000.011)
,(100.01, 100.011)
Line 669 ⟶ 710:
runTest (a, b) = do
printf "%f == %f %v\n" a b (show $ a==b) :: IO ()
printf "%f ~= %f %v\n\n" a b (show $ a~=b)</langsyntaxhighlight>
 
<pre>λ> main
Line 705 ⟶ 746:
 
J includes a "customization" conjunction ( !. ) that delivers variants of some verbs. Comparisons are tolerant by default, and their tolerance can be customized to some level. Specifying =!.0 specifies "no tolerance". Specifying a tolerance of 1e_8 is a domain error because that's no longer math. Write your own verb if you need this.
<syntaxhighlight lang="text">
NB. default comparison tolerance matches the python result
".;._2]0 :0
Line 750 ⟶ 791:
|domain error
| 2(= !.1e_8)9
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="java">public class Approximate {
private static boolean approxEquals(double value, double other, double epsilon) {
return Math.abs(value - other) < epsilon;
Line 774 ⟶ 815:
test(3.14159265358979323846, 3.14159265358979324);
}
}</langsyntaxhighlight>
{{out}}
<pre>100000000000000.020000, 100000000000000.020000 => true
Line 787 ⟶ 828:
=={{header|jq}}==
{{trans|Lobster}}
<langsyntaxhighlight lang="jq"># Return whether the two numbers `a` and `b` are close.
# Closeness is determined by the `epsilon` parameter -
# the numbers are considered close if the difference between them
Line 812 ⟶ 853:
 
tv[] | "\(.x|lpad) \(if isclose(.x; .y; 1.0e-9) then " ≈ " else " ≉ " end) \(.y|lpad)"
</syntaxhighlight>
</lang>
{{out}}
Using jq 1.6:
<langsyntaxhighlight lang="sh"> 100000000000000.02 ≈ 100000000000000.02
100.01 ≉ 100.011
1000000000.0000002 ≈ 1000000000.0000001
Line 822 ⟶ 863:
2.0000000000000004 ≈ 2
-2.0000000000000004 ≈ -2
3.141592653589793 ≈ 3.141592653589793</langsyntaxhighlight>
 
=={{header|Julia}}==
Julia has an infix operator, ≈, which corresponds to Julia's buitin isapprox() function.
{{trans|Python}}
<langsyntaxhighlight lang="julia">testvalues = [[100000000000000.01, 100000000000000.011],
[100.01, 100.011],
[10000000000000.001 / 10000.0, 1000000000.0000001000],
Line 839 ⟶ 880:
println(rpad(x, 21), " ≈ ", lpad(y, 22), ": ", x ≈ y)
end
</langsyntaxhighlight>{{out}}
<pre>
1.0000000000000002e14 ≈ 1.0000000000000002e14: true
Line 853 ⟶ 894:
=={{header|Kotlin}}==
{{trans|C#}}
<langsyntaxhighlight lang="scala">import kotlin.math.abs
import kotlin.math.sqrt
 
Line 874 ⟶ 915:
test(-sqrt(2.0) * sqrt(2.0), -2.0)
test(3.14159265358979323846, 3.14159265358979324)
}</langsyntaxhighlight>
{{out}}
<pre>1.0000000000000002E14, 1.0000000000000002E14 => true
Line 887 ⟶ 928:
=={{header|Lobster}}==
{{trans|Rust}}
<syntaxhighlight lang="lobster">
<lang Lobster>
// Return whether the two numbers `a` and `b` are close.
// Closeness is determined by the `epsilon` parameter -
Line 909 ⟶ 950:
for(tv) t:
print concat_string([string(t.x), if isclose(t.x, t.y, 1.0e-9): """ ≈ """ else: """ ≉ """, string(t.y)], "")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 924 ⟶ 965:
=={{header|Lua}}==
{{trans|C}}
<langsyntaxhighlight lang="lua">function approxEquals(value, other, epsilon)
return math.abs(value - other) < epsilon
end
Line 944 ⟶ 985:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>100000000000000.020000, 100000000000000.020000 => true
Line 956 ⟶ 997:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[CloseEnough]
CloseEnough[a_, b_, tol_] := Chop[a - b, tol] == 0
numbers = {
Line 968 ⟶ 1,009:
};
(*And@@Flatten[Map[MachineNumberQ,numbers,{2}]]*)
{#1, #2, CloseEnough[#1, #2, 10^-9]} & @@@ numbers // Grid</langsyntaxhighlight>
{{out}}
<pre>1.*10^14 1.0000000000000001*10^14 True
Line 984 ⟶ 1,025:
In order to display the values “a” and “b” as provided, without any rounding, we transmit them as strings to a comparison procedure which compute the floating point values. If the first value “a” is provided as an operation, we use a comparison procedure which accepts the computed value of “a” as second parameter. Here, “b” is never provided as an operation and can always be transmitted as a string.
 
<langsyntaxhighlight Nimlang="nim">from math import sqrt
import strformat
import strutils
Line 1,015 ⟶ 1,056:
compare("sqrt(2) * sqrt(2)", sqrt(2.0) * sqrt(2.0), "2.0")
compare("-sqrt(2) * sqrt(2)", -sqrt(2.0) * sqrt(2.0), "-2.0")
compare("3.14159265358979323846", "3.14159265358979324")</langsyntaxhighlight>
 
{{out}}
Line 1,028 ⟶ 1,069:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let approx_eq v1 v2 epsilon =
Float.abs (v1 -. v2) < epsilon
 
Line 1,045 ⟶ 1,086:
test 3.14159265358979323846 3.14159265358979324;
;;
</syntaxhighlight>
</lang>
 
=={{header|Pascal}}==
{{works with|Extended Pascal}}
The constants <tt>minReal</tt>, <tt>maxReal</tt> and <tt>epsReal</tt> are defined by the ISO standard 10206 (“Extended Pascal”).
However, their specific values are “implementation defined”, i.&nbsp;e. it is up to the compiler vendors to assign concrete values to them.
<syntaxhighlight lang="pascal">program approximateEqual(output);
 
{
\brief determines whether two `real` values are approximately equal
\param x a reference value
\param y the value to compare with \param x
\return true if \param x is equal or approximately equal to \param y
}
function equal(protected x, y: real): Boolean;
function approximate: Boolean;
function d(protected x: real): integer;
begin
d := trunc(ln(abs(x) + minReal) / ln(2)) + 1
end;
begin
approximate := abs(x - y) <= epsReal * (maxReal / (d(x) + d(y)))
end;
begin
equal := (x = y) or_else (x * y >= 0.0) and_then approximate
end;
 
{ --- auxilliary routines ---------------------------------------------- }
procedure test(protected x, y: real);
const
{ ANSI escape code for color coding }
CSI = chr(8#33) + '[';
totalMinimumWidth = 40;
postRadixDigits = 24;
begin
write(x:totalMinimumWidth:postRadixDigits, '':1, CSI, '1;3');
if equal(x, y) then
begin
if x = y then
begin
write('2m≅')
end
else
begin
write('5m≆')
end
end
else
begin
write('1m≇')
end;
writeLn(CSI, 'm', '':1, y:totalMinimumWidth:postRadixDigits)
end;
 
{ === MAIN ============================================================= }
var
n: integer;
x: real;
begin
{ Variables were used to thwart compile-time evaluation done }
{ by /some/ compilers potentially confounding the results. }
n := 2;
x := 100000000000000.01;
test(x, 100000000000000.011);
test(100.01, 100.011);
test(x / 10000.0, 1000000000.0000001000);
test(0.001, 0.0010000001);
test(0.000000000000000000000101, 0.0);
x := sqrt(n);
test(sqr(x), 2.0);
test((-x) * x, -2.0);
test(3.14159265358979323846, 3.14159265358979324)
end.</syntaxhighlight>
{{out}}
100000000000000.015625000000000000000000 ≅ 100000000000000.015625000000000000000000
100.010000000000005115907697 ≆ 100.010999999999995679900167
10000000000.000001907348632812500000 ≆ 1000000000.000000119209289550781250
0.001000000000000000020817 ≇ 0.001000000100000000054917
0.000000000000000000000101 ≇ 0.000000000000000000000000
2.000000000000000444089210 ≆ 2.000000000000000000000000
-2.000000000000000444089210 ≆ -2.000000000000000000000000
3.141592653589793115997963 ≅ 3.141592653589793115997963
The shown output was generated by a <tt>program</tt> compiled by the GPC (GNU Pascal Compiler).
Due to technical limitations it was not possible to reproduce 100.01&nbsp;≆&nbsp;100.011 as requested by the task specification.
The computer had an IEEE-754-compliant FPU with 80-bit precision.
Note that Pascal’s <tt>write</tt>/<tt>writeLn</tt>/<tt>writeStr</tt> routines (the last one is only available in Extended Pascal) produce ''rounded'' representations.
 
=={{header|Perl}}==
Passes task tests, but use the module <code>Test::Number::Delta</code> for anything of real importance.
<langsyntaxhighlight lang="perl">use strict;
use warnings;
 
Line 1,081 ⟶ 1,210:
my $real_pi = 2 * atan2(1, 0);
my $roman_pi = 22/7;
is_close($real_pi,$roman_pi,$_) for <10 3>;</langsyntaxhighlight>
{{out}}
<pre>True 100000000000000.0 ≅ 100000000000000.0
Line 1,103 ⟶ 1,232:
I got a different result for test 4 to everyone else, but simply setting the cfmt to "%.10f" got it the NOT.<br>
Likewise something similar for the trickier/ambiguous test 5, for which "0.000000" is as good as anything I can do, and both now show how to get either a true or false result.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">dfmt</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"%g"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cfmt</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"%g"</span><span style="color: #0000FF;">)</span>
Line 1,124 ⟶ 1,253:
<span style="color: #000000;">test</span><span style="color: #0000FF;">(-</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)*</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),-</span><span style="color: #000000;">2.0</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3.14159265358979323846</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3.14159265358979324</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%.20f"</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
64 bit (implied by some of the accuracies specified for this task):
Line 1,171 ⟶ 1,300:
3.1415926535897931 and
3.1415926535897931 are approximately equal
</pre>
 
=={{header|Processing}}==
<syntaxhighlight lang="processing">double epsilon = 1e-18D;
 
void setup() {
testIsClose(100000000000000.01D, 100000000000000.011D, epsilon);
testIsClose(100.01D, 100.011D, epsilon);
testIsClose(10000000000000.001D / 10000.0D, 1000000000.0000001000D, epsilon);
testIsClose(0.001D, 0.0010000001D, epsilon);
testIsClose(0.000000000000000000000101D, 0.0D, epsilon);
testIsClose(Math.sqrt(2) * Math.sqrt(2), 2.0D, epsilon);
testIsClose(-Math.sqrt(2) * Math.sqrt(2), -2.0D, epsilon);
testIsClose(3.14159265358979323846D, 3.14159265358979324D, epsilon);
exit(); // all done
}
 
 
boolean isClose(double num1, double num2, double epsilon) {
return Math.abs(num2 - num1) <= epsilon;
}
 
 
void testIsClose(double num1, double num2, double epsilon) {
boolean result = isClose(num1, num2, epsilon);
if (result) {
println("True. ", num1, "is close to", num2);
} else {
println("False. ", num1, "is not close to", num2);
}
}</syntaxhighlight>
 
{{Output}}
<pre>
True. 1.0000000000000002E14 is close to 1.0000000000000002E14
False. 100.01 is not close to 100.011
False. 1.0000000000000002E9 is not close to 1.0000000000000001E9
False. 0.001 is not close to 0.0010000001
True. 1.01E-22 is close to 0.0
False. 2.0000000000000004 is not close to 2.0
False. -2.0000000000000004 is not close to -2.0
True. 3.141592653589793 is close to 3.141592653589793
</pre>
 
Line 1,194 ⟶ 1,365:
only close to themselves.
</pre>
<langsyntaxhighlight lang="python">from numpy import sqrt
from math import isclose
 
Line 1,210 ⟶ 1,381:
print(x, maybenot, "approximately equal to ", y)
 
</langsyntaxhighlight>{{out}}
<pre>
100000000000000.02 is approximately equal to 100000000000000.02
Line 1,223 ⟶ 1,394:
=={{header|R}}==
The base library has the function all.equal() for this task. However, when the numbers are not equal, rather than return FALSE, it tries to explain the difference. To fix this, we use isTRUE(all.equal(....)) instead.
<langsyntaxhighlight lang="rsplus">approxEq <- function(...) isTRUE(all.equal(...))
tests <- rbind(c(100000000000000.01, 100000000000000.011),
c(100.01, 100.011),
Line 1,235 ⟶ 1,406:
#All that remains is to print out our results in a presentable way:
printableTests <- format(tests, scientific = FALSE)
print(data.frame(x = printableTests[, 1], y = printableTests[, 2], Equal = results, row.names = paste0("Test ", 1:8, ": ")))</langsyntaxhighlight>
{{out}}
<pre> x y Equal
Line 1,251 ⟶ 1,422:
In Racket, a number literal with decimal point is considered a flonum, an inexact number which could be either 30 or 62 bits depending on machines. By prefixing the literal with <code>#e</code>, it is now considered an exact, rational number. In this task, we test the approximate equality on both variants:
 
<langsyntaxhighlight lang="racket">#lang racket
 
(define (≈ a b [tolerance 1e-9])
Line 1,284 ⟶ 1,455:
(match-define (list a b) test)
(printf "~a ~a: ~a\n" (format-num a) (format-num b) (≈ a b)))
(newline))</langsyntaxhighlight>
 
{{out}}
Line 1,320 ⟶ 1,491:
For example, in Raku, the sum of .1, .2, .3, & .4 is ''identically'' equal to 1.
 
<syntaxhighlight lang="raku" perl6line>say 0.1 + 0.2 + 0.3 + 0.4 === 1.0000000000000000000000000000000000000000000000000000000000000000000000000; # True</langsyntaxhighlight>
 
It's also ''approximately'' equal to 1 but... ¯\_(ツ)_/¯
 
<syntaxhighlight lang="raku" perl6line>for
100000000000000.01, 100000000000000.011,
100.01, 100.011,
Line 1,345 ⟶ 1,516:
my $*TOLERANCE = .001;
say 22/7, " ≅ ", π, ": ", 22/7 ≅ π;
}</langsyntaxhighlight>
{{out}}
<pre>100000000000000.01 ≅ 100000000000000.011: True
Line 1,362 ⟶ 1,533:
 
=={{header|ReScript}}==
<langsyntaxhighlight lang="rescript">let approx_eq = (v1, v2, epsilon) => {
abs_float (v1 -. v2) < epsilon
}
Line 1,381 ⟶ 1,552:
test(3.14159265358979323846, 3.14159265358979324)
}
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
Line 1,388 ⟶ 1,559:
 
The choosing of the number of decimal digits is performed via the REXX statement: &nbsp; '''numeric digits &nbsp; ''nnn'' '''
<langsyntaxhighlight lang="rexx">/*REXX program mimics an "approximately equal to" for comparing floating point numbers*/
numeric digits 15 /*what other FP hardware normally uses.*/
@.= /*assign default for the @ array. */
Line 1,417 ⟶ 1,588:
numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g=g *.5'e'_ %2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g/1</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
Line 1,464 ⟶ 1,635:
B= 100000000000000004.0
A approximately equal to B? true
</pre>
 
=={{header|RPL}}==
We use here mantissa comparison, which makes that any epsilon can not be close to zero.
≪ MANT SWAP MANT - ABS 1E-09 <
≫ ‘'''CLOSE?'''’ STO
 
≪ {} { 100000000000000.01 100000000000000.011
100.01 100.011
≪ 10000000000000.001 10000 / ≫ 1000000000.0000001
0.001 0.0010000001
0.000000000000000000000101 0
≪ 2 √ 2 √ * ≫ 2
≪ 2 √ 2 √ * NEG ≫ -2
3.14159265358979323846, π }
1 OVER SIZE '''FOR''' j
DUP j GET EVAL OVER j 1 + GET EVAL '''CLOSE?'''
NUM→ "True" "False" IFTE ROT SWAP + SWAP 2 '''STEP'''
≫ ‘'''TASK'''’ STO
{{out}}
<pre>
1: { "True" "False" "True" "False" "False" "True" "True" "True" }
</pre>
 
=={{header|Ruby}}==
Most work went into handling weird Float values like NaN and Infinity.
<langsyntaxhighlight lang="ruby">require "bigdecimal"
 
testvalues = [[100000000000000.01, 100000000000000.011],
Line 1,495 ⟶ 1,688:
puts "#{a} #{a.close_to?(b) ? '≈' : '≉'} #{b}"
end
</syntaxhighlight>
</lang>
{{out}}
<pre>100000000000000.02 ≈ 100000000000000.02
Line 1,510 ⟶ 1,703:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">/// Return whether the two numbers `a` and `b` are close.
/// Closeness is determined by the `epsilon` parameter -
/// the numbers are considered close if the difference between them
Line 1,535 ⟶ 1,728:
test!(-sqrt(2.0) * sqrt(2.0), -2.0);
test!(3.14159265358979323846, 3.14159265358979324);
}</langsyntaxhighlight>
{{out}}
<pre> 100000000000000.01 ≈ 100000000000000.011
Line 1,548 ⟶ 1,741:
{{Out}}Best seen running in your browser by [https://scastie.scala-lang.org/kxD9xQuIQEGpABXnsE6BiQ Scastie (remote JVM)].
 
<langsyntaxhighlight Scalalang="scala">object Approximate extends App {
val (ok, notOk, ε) = ("👌", "❌", 1e-18d)
 
Line 1,567 ⟶ 1,760:
test(BigDecimal(-Math.sqrt(2) * Math.sqrt(2)), BigDecimal(-2.0), false)
test(BigDecimal("3.14159265358979323846"), BigDecimal("3.14159265358979324"), true)
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
Two values can be compared for approximate equality by using the built-in operator '''≅''', available in ASCII as '''=~=''', which does approximate comparison by rounding both operands at '''(PREC>>2)-1''' decimals. However, by default, Sidef uses a floating-point precision of 192 bits.
<langsyntaxhighlight lang="ruby">[
100000000000000.01, 100000000000000.011,
100.01, 100.011,
Line 1,586 ⟶ 1,779:
].each_slice(2, {|a,b|
say ("#{a} ≅ #{b}: ", a ≅ b)
})</langsyntaxhighlight>
{{out}}
<pre>
Line 1,605 ⟶ 1,798:
The Number '''n.round(-k)''' can be used for rounding the number ''n'' to ''k'' decimal places. A positive argument can be used for rounding before the decimal point.
 
<langsyntaxhighlight lang="ruby">var a = 100000000000000.01
var b = 100000000000000.011
 
# Rounding at 2 and 3 decimal places, respectively
say (round(a, -2) == round(b, -2)) # true
say (round(a, -3) == round(b, -3)) # false</langsyntaxhighlight>
 
There is also the built-in '''approx_cmp(a, b, k)''' method, which is equivalent with '''a.round(k) <=> b.round(k)'''.
 
<langsyntaxhighlight lang="ruby">var a = 22/7
var b = Num.pi
 
say ("22/7 ≅ π at 2 decimals: ", approx_cmp(a, b, -2) == 0)
say ("22/7 ≅ π at 3 decimals: ", approx_cmp(a, b, -3) == 0)</langsyntaxhighlight>
 
{{out}}
Line 1,628 ⟶ 1,821:
Additionally, the '''rat_approx''' method can be used for computing a very good rational approximation to a given real value:
 
<langsyntaxhighlight lang="ruby">say (1.33333333.rat_approx == 4/3) # true
say (zeta(-5).rat_approx == -1/252) # true</langsyntaxhighlight>
 
Rational approximations illustrated for substrings of PI:
<langsyntaxhighlight lang="ruby">for k in (3..19) {
var r = Str(Num.pi).first(k)
say ("rat_approx(#{r}) = ", Num(r).rat_approx.as_frac)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,661 ⟶ 1,854:
There are slight differences in how this is named in the various dialects &sup1;. If required, you have to add a forwarding alias method to Number.
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">{ #(100000000000000.01 100000000000000.011) .
#(100.01 100.011) .
{10000000000000.001 / 10000.0 . 1000000000.0000001000} .
Line 1,671 ⟶ 1,864:
} pairsDo:[:val1 :val2 |
Stdout printCR: e'{val1} =~= {val2} -> {val1 isAlmostEqualTo:val2 nEpsilon:2}'
]</langsyntaxhighlight>
In CUIS, this method is called <tt>isWithin:floatsFrom:</tt>.
{{out}}
Line 1,687 ⟶ 1,880:
Using the solution proposed as an addition to the Swift standard library in SE-0259. Currently this is not accepted, but is likely to be included in the Swift Numerics module.
 
<langsyntaxhighlight lang="swift">import Foundation
 
extension FloatingPoint {
Line 1,754 ⟶ 1,947:
for testCase in testCases {
print("\(testCase.0), \(testCase.1) => \(testCase.0.isAlmostEqual(to: testCase.1))")
}</langsyntaxhighlight>
 
{{out}}
Line 1,770 ⟶ 1,963:
===Using decimal library===
Uses tcllib's decimal library. Using a tolerance of 9 significant digits.
<langsyntaxhighlight Tcllang="tcl">catch {namespace delete test_almost_equal_decimal} ;# Start with a clean namespace
 
namespace eval test_almost_equal_decimal {
Line 1,805 ⟶ 1,998:
}
}
</langsyntaxhighlight>{{out}}
<pre>Is 100000000000000.01 ≈ 100000000000000.011 ? Yes.
Is 100.01 ≈ 100.011 ? No.
Line 1,817 ⟶ 2,010:
 
===Using string manipulation===
<langsyntaxhighlight Tcllang="tcl">catch {namespace delete test_almost_equal_string} ;# Start with a clean namespace
 
namespace eval test_almost_equal_string {
Line 1,860 ⟶ 2,053:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Is 100000000000000.01 ≈ 100000000000000.011 ? Yes.
Line 1,874 ⟶ 2,067:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports System.Runtime.CompilerServices
 
Module Module1
Line 1,899 ⟶ 2,092:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>100000000000000, 100000000000000 => True
Line 1,911 ⟶ 2,104:
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var tol = 1e-16
var pairs = [
[100000000000000.01, 100000000000000.011],
Line 1,927 ⟶ 2,120:
i = i + 1
System.print(" %(i) -> %((pair[0] - pair[1]).abs < tol)")
}</langsyntaxhighlight>
 
{{out}}
Line 1,943 ⟶ 2,136:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">func ApproxEqual(A, B); \Return 'true' if approximately equal
real A, B;
real Epsilon;
Line 1,967 ⟶ 2,160:
CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 1,980 ⟶ 2,173:
8. 3.1415926535897900E+000 3.1415926535897900E+000 true
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Approximate_equality
// by Jjuanhdez, 09/2022
 
epsilon = 1.0
while (1 + epsilon <> 1)
epsilon = epsilon / 2
wend
 
print "epsilon = ", epsilon
print
eq_approx(100000000000000.01, 100000000000000.011)
eq_approx(100.01, 100.011)
eq_approx(10000000000000.001/10000.0, 1000000000.0000001000)
eq_approx(0.001, 0.0010000001)
eq_approx(0.000000000000000000000101, 0.0)
eq_approx(sqrt(2)*sqrt(2), 2.0)
eq_approx(-sqrt(2)*sqrt(2), -2.0)
eq_approx(3.14159265358979323846, 3.14159265358979324)
end
 
sub eq_approx(a, b)
tmp = abs(a - b) < epsilon
print tmp, " ", a, " ", b
end sub</syntaxhighlight>
 
=={{header|zkl}}==
Line 1,985 ⟶ 2,204:
and tolerance. If the tolerance is >=0, comparison is absolute.
If tolerance is <0 (and x!=0 and y!=0), the comparison is relative.
<langsyntaxhighlight lang="zkl">testValues:=T(
T(100000000000000.01,100000000000000.011),
T(100.01, 100.011),
Line 2,001 ⟶ 2,220:
maybeNot:=( if(x.closeTo(y,tolerance)) " \u2248" else "!\u2248" );
println("% 25.19g %s %- 25.19g %g".fmt(x,maybeNot,y, (x-y).abs()));
}</langsyntaxhighlight>
 
{{out}}
9,476

edits