P
Pavils Jurjans
Hallo,
It is know issue that due to the fact that computer has to store the real
numbers in limited set of bytes, thus causing a minor imprecision from the
decimal value that likely was stored. I don't know, how dotnet framework
stored doubles, but it's certain, that if I store, say, 1.234567 in some
real variable, it is stored in memory like something close to
1.2345670000000000000003454786544 or
1.234566999999999999999999999999999924354324.
Due to this problem it may sometimes cause some unexpected results when
comparing the real numbers in "if" statement.
Some programming languages have built-in protection, that compares only
limited number of digits (less than declared capability of the type), when
asked to compare two real numbers, thus the garbage in the lesser decimal
fields goes unnoticed. I have been using an "ApproximatelyEqual" method, for
comparing two real numbers and providing precision:
input: A, B, precision
output: (abs(A-B) <= 10^(-precision))
Example:
A = 1.00000000000001
B = 1.00000000000007
precision = 13
abs(A-B) = 0.00000000000006
10^(-precision) = 0.0000000000001
abs(A-B) <= 10^(-precision) = true
precision = 14
10^(-precision) = 0.00000000000001
abs(A-B) <= 10^(-precision) = false
For a project I am working on, where there are done multiple operations with
real numbers, I wanted to be sure, where there are some traps I may fall in.
Is it safe to compare the real numbers without custom "ApproximatelyEqual"
method?
Thanks,
Pavils
It is know issue that due to the fact that computer has to store the real
numbers in limited set of bytes, thus causing a minor imprecision from the
decimal value that likely was stored. I don't know, how dotnet framework
stored doubles, but it's certain, that if I store, say, 1.234567 in some
real variable, it is stored in memory like something close to
1.2345670000000000000003454786544 or
1.234566999999999999999999999999999924354324.
Due to this problem it may sometimes cause some unexpected results when
comparing the real numbers in "if" statement.
Some programming languages have built-in protection, that compares only
limited number of digits (less than declared capability of the type), when
asked to compare two real numbers, thus the garbage in the lesser decimal
fields goes unnoticed. I have been using an "ApproximatelyEqual" method, for
comparing two real numbers and providing precision:
input: A, B, precision
output: (abs(A-B) <= 10^(-precision))
Example:
A = 1.00000000000001
B = 1.00000000000007
precision = 13
abs(A-B) = 0.00000000000006
10^(-precision) = 0.0000000000001
abs(A-B) <= 10^(-precision) = true
precision = 14
10^(-precision) = 0.00000000000001
abs(A-B) <= 10^(-precision) = false
For a project I am working on, where there are done multiple operations with
real numbers, I wanted to be sure, where there are some traps I may fall in.
Is it safe to compare the real numbers without custom "ApproximatelyEqual"
method?
Thanks,
Pavils