Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do you use for fixed point representation in C++?

Tags:

I'm looking for a fixed-point standard to use for financial data, do you know any that is worth trying? Do you have any experience on the performance of that hand-made fixed-point classes?

like image 356
Edwin Jarvis Avatar asked Sep 28 '08 16:09

Edwin Jarvis


People also ask

What is fixed-point representation in C?

Fixed-Point Representation −This representation has fixed number of bits for integer part and for fractional part. For example, if given fixed-point representation is IIII. FFFF, then you can store minimum value is 0000.0001 and maximum value is 9999.9999.

How do you represent a fixed-point?

In computing, fixed-point refers to a method of representing fractional (non-integer) numbers by storing a fixed number of digits of their fractional part. Dollar amounts, for example, are often stored with exactly two fractional digits, representing the cents (1/100 of dollar).

What is fixed-point data representation?

Fixed-point representation has a radix point known as decimal point. Fixed-point numbers having decimal points at the right end of the number are treated as integers because the fixed-point numbers having decimal points at the left end of the number are treated as fractions.

How do you represent a floating-point in C?

Floating-point constants are positive unless they're preceded by a minus sign ( - ). In this case, the minus sign is treated as a unary arithmetic negation operator. Floating-point constants have type float , double , or long double . The Microsoft C compiler internally represents long double the same as type double .


2 Answers

Dr.Dobb's has an article about a possible implementation of fixed-point arithmetic type in C++. Check this out.

like image 111
Nicola Bonelli Avatar answered Sep 26 '22 03:09

Nicola Bonelli


Ouch. Financial systems are tricky, your main problem is not fixed point math, the problem are the rounding errors.

You can have a nice spreadsheet full with maverlous calculations with discounts by client type and VAT included. You make a total, you present it to an accountant and he says the values are all wrong. The reason: The output may be formated with only 2 decimal places but internally the value has all the decimal places of a float or double. and they do add up.

You need to know your financials and decide where the base values will be. Meaning what values are the ones the accountants will check (yes it requires business knowledge, hance the 'tricky' part).

The before you save the value to a persistent form (database, file, memory ...) you truncate the extra decimal places that multiplications and divisions may have added.

Quick and dirty solution for N decimal places: ((double)((int)(Value * N * 10.0)))/10.0

Of course you need to check exactly which kind of rounding do your financials require.

like image 36
Caerbanog Avatar answered Sep 26 '22 03:09

Caerbanog