How to resolve the algorithm Approximate equality step by step in the Processing programming language
How to resolve the algorithm Approximate equality step by step in the Processing programming language
Table of Contents
Problem Statement
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between 32 bit and 64 bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic.
Create a function which returns true if two floating point numbers are approximately equal.
The function should allow for differences in the magnitude of numbers, so that, for example, 100000000000000.01 may be approximately equal to 100000000000000.011, even though 100.01 is not approximately equal to 100.011. If the language has such a feature in its standard library, this may be used instead of a custom function. Show the function results with comparisons on the following pairs of values:
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Approximate equality step by step in the Processing programming language
Source code in the processing programming language
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);
}
}
You may also check:How to resolve the algorithm Loops/For step by step in the blz programming language
You may also check:How to resolve the algorithm Modular inverse step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Combinations step by step in the Picat programming language
You may also check:How to resolve the algorithm Hello world/Standard error step by step in the MATLAB / Octave programming language
You may also check:How to resolve the algorithm 99 bottles of beer step by step in the Hope programming language