views:

71

answers:

2

I have the following code:

typedef __int64 BIG_INT;
typedef double CUT_TYPE;

#define CUT_IT(amount, percent) (amount * percent)

void main()
{
    CUT_TYPE cut_percent = 1;

    BIG_INT bintOriginal = 0x1FFFFFFFFFFFFFF;
    BIG_INT bintAfter = CUT_IT(bintOriginal, cut_percent);
}

bintAfter's value after the calculation is 144115188075855872 instead of 144115188075855871 (see the "2" in the end, instead of "1"??).

On smaller values such as 0xFFFFFFFFFFFFF I get the correct result.
How do I get it to work, on 32bit app? What do I have to take in account?
My aim is to cut a certain percentage of a very big number.

I use VC++ 2008, Vista.

+2  A: 

Floating point calculations aren't guaranteed to be perfectly accurate, and you've defined CUT_TYPE as double.

See this answer for more info: http://stackoverflow.com/questions/590822/dealing-with-accuracy-problems-in-floating-point-numbers/590851#590851

Mark Ransom
I know I should "accept" a certain range, although hoping for someone to come up with a way around this.
Poni
The way around it is to use a bignumber library that supports arbitrary precision, and rational numbers.
Ben Voigt
+5  A: 

double has a 52 bit mantissa, you're losing precision when you try to load a 60+ bit value into it.

bstpierre
I usually use 'long double' on g++, which gives greater precision. Having just checked though, it appears that VC++ doesn't really respect this. http://en.wikipedia.org/wiki/Long_double
Aaron McDaid