3

Given that 8-byte doubles can represent all 4-byte ints precisely, I'm wondering whether dividing a double A storing an int, by a double B storing an int (such that the integer B divides A) will always give the exact double corresponding to the integer that is their quotient? So, if B and C are integers, and B*C fits within a 32-bit int, then is it guaranteed that

int B,C = whatever s.t. B*C does not overflow 32-bit int
double(B*C)/double(C) == double((B*C)/C) ?

Does the IEEE754 standard guarantee this?

In my testing, it seems to work for all examples I've tried. In Python:

>>> (321312321.0*3434343.0)/321312321.0 == 3434343.0
True

The reason for asking is that Matlab makes it hard to work with ints, so I often just use the default doubles for integer calculations. And when I know that the integers are exactly divisible, and if I know that the answer to the present question is yes, then I could avoid doing casts to ints, idivide(..) etc., which is less readable.

Community
  • 1
  • 1
Evgeni Sergeev
  • 22,495
  • 17
  • 107
  • 124

1 Answers1

1

Luis Mendo's comment does answer this question, but to specifically address the use in Matlab there are some handy utilities described here. You can use eps(numberOfInterest) to find the distance to the next largest double-precision floating point number. For example:

eps(1) = 2^(-52)
eps(2^52) = 1

This practically guarantees that mathematical operations with integers held in a double will be precise provided they don't overflow 2^52, which is quite a bit larger than what is held in a 32-bit int type.

Michael Repucci
  • 1,633
  • 2
  • 19
  • 35
  • So, is the result of an operation on doubles guaranteed to be the **nearest** double to the actual result? I was under the impression that was what Java's StrictMath was for http://docs.oracle.com/javase/7/docs/api/java/lang/StrictMath.html while ordinary (trade-off between fast and accurate) operations could lead to tiny errors in the last binary digit or two. – Evgeni Sergeev Apr 23 '14 at 00:15
  • I'm not familiar with Java or StrictMath, but I read the documentation as saying that "strict" refers to "[the algorithms in StrictMath] produce the same results as ... published algorithms ... from the well-known ... package ... fdlibm". That is, StrictMath methods guarantee that you will get the same results as you would obtain with methods from fdlibm. It's definitely the case that the algorithms used for mathematical functions have fast and less-accurate or slower and more-precise flavors. But, unless I'm mistaken, division only has one algorithm, so that concern doesn't apply here. – Michael Repucci Apr 23 '14 at 14:05
  • For what it's worth, The Mathworks is generally transparent about what algorithms they use in each Matlab function (see documentation). So if you're interested in a particular mathematical function, you should be able to explore that more carefully. – Michael Repucci Apr 23 '14 at 14:07