Approximate equality: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(11 intermediate revisions by 2 users not shown)
Line 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,593 ⟶ 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>
 
Line 2,040 ⟶ 2,104:
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascriptwren">var tol = 1e-16
var pairs = [
[100000000000000.01, 100000000000000.011],
9,476

edits