0

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.

Community
  • 1
  • 1
Alex
  • 15,186
  • 15
  • 73
  • 127

2 Answers2

4

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.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • Thanks, is my original expression still true if `T` is not subject to overflow issues? – Alex May 05 '16 at 01:45
  • Suppose that `a+b` caused overflow, and `c` was negative enough such that `a+b+c` (and thus `T`) were representable. This could cause `a+b+c==T` to not be true. – Scott Hunter May 05 '16 at 01:49
  • Ok, I take your point, but suppose there are no overflow issues anytime a sum is evaluated. Is the result still true? – Alex May 05 '16 at 01:51
  • 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. – Cyb3rFly3r May 05 '16 at 03:26
3

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.

Cyb3rFly3r
  • 1,321
  • 7
  • 12