Question

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.

Was it helpful?

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.

OTHER TIPS

if you are working with big integers, why not try to write a bigint class instead of using long double? check this:

sample c++ code of a big int class

How to implement big int in C++

Do you know how long, in bits, the largest value you need to handle is?

I ask because I noticed that gcc, on some platforms, supports 128 bit integers:
http://gcc.gnu.org/onlinedocs/gcc/_005f_005fint128.html

so you might be very lucky, if you can get at a platform which supports 128 bit long long, and an up-to-date gcc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top