Is integer multiplication implemented using double

2020-06-19 10:26发布

问题:

I ask because I am computing matrix multiplications where all the matrix values are integers.

I'd like to use LAPACK so that I get fast code that is correct. Will two large integers (whose product is less than 2^53), stored as doubles, when multiplied, yield a double containing the exact integer result?

回答1:

Your analysis is correct:

  • All integers between -253 and 253 are exactly representable in double precision.
  • The IEEE754 standard requires calculations to be performed exactly, and then rounded to the nearest representable number.

Hence a product of two values that equals an integer in that range will therefore be represented exactly.

Reference: What every computer scientist should know about floating-point arithmetic. The key section is the discussion of the IEEE standard as pertaining to operations. That contains the statement of the second bullet point above. You already knew the first bullet point and it's the second point that completes the argument.



回答2:

Yes! A double's data is split into its sign, exponent, and fraction:

Wikipedia has an article explaining the ranges of representable numbers

All integers between -2^53 and 2^53 are representable in double precision.

Between 2^52=4,503,599,627,370,496 and 2^53=9,007,199,254,740,992 the representable numbers are exactly the integers. For the next range, from 2^53 to 2^54, everything is multiplied by 2, so the representable numbers are the even ones, etc. Conversely, for the previous range from 2^51 to 2^52, the spacing is 0.5, etc.