Search code examples
c++doubleprecisionmultiplicationlong-double

Double precision: Multiplication of big numbers


I have some simple operations (subtraction, multiplication) with big numbers (integers). They are so big, that I have to store them into long double variable. That is fine, but for some cases multiplication looses precision.

Example:

A = 84478098072866400.00
B = 419247971803584000000.00

A * B = 35417271278873496315650351919301394432.00

It is obvious, that this is wrong. Result of multiplication should end with sequence of zeros.

I need to keep precision, especially this one (when numbers ends with zeros) because this is the most common case.

My question is, how to do that, please? Is there any way how to force long double to behave better? Or is there any option how to get precision of stored number?

Thanks a lot!

EDIT:

I cannot use any external library. I am trying to solve one problem of ACM competition archive. This is part of it.

I would be fine with precision lost, but I have to detect it. When the numbers are bigger than long double that it is highly probable (maybe certain), that it ends with long sequence of zeros.


Solution

  • If you're really working with huge integers, you'll want to do arbitrary precision arithmetic where only memory limits the size of your numbers (and no precision is lost). The GNU Multiple Precision Arithmetic Library is a popular library for this (and arbitrary precision arithmetic on rationals and floating point numbers as well), though I'm sure there are others.