Reputation: 15718
As this example suggests:
0.1 + 0.1 + 0.1 == 0.3
gives the surprising result of false due to precision issues when storing 0.1
.
However,
1 + 1 + 1 == 3
evaluates to true as expected. Note that there is still the issue of comparison of floating numbers here. As pointed out in the comments, the default numeric data type is double unless specified otherwise.
My question is, if a + b + c + ...= T
, and a
, b
, c
, ... , T
are all integers, is the evaluated value of
a + b + c + ... == T
always true?
What other ways are there to relax the condition of a
, b
, c
, ... , T
being integers and still maintain the truth of the above statement?
As helpfully pointed out in one answer, any sort of overflow encountered at any point of the evaluation will cause this to evaluate to false:
A = realmax('double')
A - A + A == A % evaluates to true
A + A - A == A % evaluates to false
Thus, for the purposes of my original question, assume that no overflow problems at encountered at any stage necessary to evaluate the expression.
Upvotes: 0
Views: 104
Reputation: 1341
If you think about how integers are represented in floating point notation, as long as there is no representation error there will be no problem with equality comparison. For "small" integers it is never an issue, because you have plenty of bits for the mantissa and they can be represented exactly. If you try adding very (really) large integers, then issues may arise:
>> 2^50 == 2^50+1
ans =
0
While:
>> 2^53 == 2^53+1
ans =
1
This is the overflow that Scott Hunter is talking about. Look for IEEE Standard 754 to learn more about the representation of floating point numbers.
Upvotes: 3
Reputation: 49883
If integers are represented using fixed-sized data types, then there is a limit to how large (in magnitude) a number can be represented. Thus, if a calculation would go over that limit (a condition known as overflow), the result would not be correct.
Upvotes: 4