I should have precised that all values on those arrays have been set up manually with integer numbers and haven't been altered at all since then, so there shouldn't be any imprecision at all in that case, if I got it well.
double x = 5.000;
int y = 5;
if( abs(x-(double)y) < 0.01 ) // If the difference between x and y is less than 0.01...
// 0.01 is the value you want to use as a "Rounding Error"
{
// They are almost equal
}
else
{
// They aren't equal at all
}
And you can create a function like this:
1 2 3 4 5 6 7
bool isDoubleEqual(double x, int y, double RoundingError = 0.01)
{
return ( abs(x - (double)y) < RoundingError);
// What it actually does, is to take the difference between the numbers,
// And return a positive-only number, so if difference is 0, 0.1 or -0.1,
// it will return 0, 0.1 and 0.1. So you can check their difference in a faster way
}
double x = 5.005;
int y = 5;
if(isDoubleEqual(x,y)) // You don't need to give a third value, it is a
// default value (see "Double RoundingError = 0.01", 0.01 is the default value)
{
// Is Almost Equal
// Will Be Executed
}
else
{
// Is Not
}
// This will give you a "Almost Equal" result.
// But the following will not:
if(isDoubleEqual(x,y,0.001)) // x - y is more than 0.001,
// so they are NOT equal with this rounding error check
{
// Is Almost Equal
}
else
{
// Is not
// Will Be Executed
}
@Moschops
Unfortunately, floating-point stuff doesn't work that way. The example you gave does not actually match the way that floating-point arithmetic works in the OPs example.
@EssGeEichbool isDoubleEqual(double x, double y, double RoundingError = 0.01)
An int will type-promote to a double, so this version will be more friendly in a lot of ways. Nice!
The link doesn't mention any difference (that I can see - I have not read it cover to cover) between dereferencing a double/int from arrays (OP's example) and comparing them, and just comparing double/int (my example).
@Duoas , Well, I made the second parameter an Int so he will not get a Compiler Warning for Implicit Type Casting... But maybe you are "right-er" than me, because if he inverts the values, the function will have a different result.
The entire bottom half of the paper deals with it... but put simply, there are precision errors that aggregate when transferring the number around in the computer. What looks like one line of code can involve a number of FPU stack operations -- which can easily change your number in miniscule ways, and make simplistic comparisons fail.
Thank you. I appreciate not having to read it; I'm not a computer scientist, I'm a hack (not hacker, just a hack; the coding equivalent of a hack journalist).
LOL, I just posted the link. When you said you didn't get anything out of it, I took another look and remembered that it was fairly technical. I'm sure there is a more friendly writeup somewhere, but I didn't care to google it ATM.
FP stuff has a surprising number of gotchas when you think you are dealing with normal numbers.