Addition seems odd

Big<2, 2> n, a;
n = 0;
a = "0.0000000001";
string nstring;

for(unsigned int i=0; n < 10000; n+=a, i++)

Watch the console output...
after not even 1000 iterations the output becomes wrong.
I looks like it is not adding "a", but a value wich is
just a little bit smaller.

Iam sure you have tested your library.
So Iam asking: What the heck am I doing wrong?? Why is
there an error in such a simple calculation?

Added by: tomek, 2009 X 10, Last modified: 2009 X 10

a = "0.0000000001";

Here is the 'problem'. TTMath is a binary floating point numbers, not *decimal* floating point numbers. It means that decimal '0.0000000001' must be converted to a binary representation first. It is:
1,10110111110011011111110110011101011110111(....) *10^-100010
In other words there is not *exact* binary representation of decimal '0.0000000001'. The binary value is a little lower. And now you have your answer.

The same thing is in 'float' or 'double', consider this:
double n, a;
n = 0.0;
a = 0.0001;

while( n < 1.0 )
n += a;

std::cout << n << std::endl;

Above program displays 1.0001 (not 1.0 as you may expect to).

You should read about accuracy in binary floating point numbers.
section 'Accuracy problems'.

Added by: ~Felheart, 2009 X 22

Thank you for your answer.
I understand the problem now, but is there anything I can do to avoid this problem with ttmath?
Because of the "imperfect" representation of the number I already tried to increase the amount of bits used to represent
each number.

I wrote "Big<10, 100>" but something is still wrong.
My seconds try was to use a fixed point number system,
by dividing a Int<200> by 10^20 each time i needed to print it out...
But that doesn't solve the problem :)

Added by: tomek, 2009 X 25

Sorry but there is not any solution, if you really need 0.0001 you have to use decimal library (not binary).

Added by: ~Manveru, 2010 I 20

The TTmath library could support Q form of numbers, which is fixed point arithmetic.

If it already support long integers the only thing to implement is proper dot positioning during multiplication and division. Look at:

Added by: tomek, 2010 I 24

This is a good idea, I'll take it into consideration when I have some spare time.