Compare storing order book prices as a double, as a scaled 64-bit integer in ticks, and as a decimal type, for an instrument quoted in increments of 0.01. Give a concrete case where the double is wrong and say what the exchange's own representation implies.
Compare storing order book prices as a double, as a scaled 64-bit integer in ticks, and as a decimal type, for an instrument quoted in increments of 0.01. Give a concrete case where the double is wrong and say what the exchange's own representation implies.
Approach: Consider which decimal values are exactly representable in binary floating point, then follow an inexact price through a comparison and an accumulation.
Store prices as scaled 64-bit integers in ticks, which is fixed point arithmetic, because 0.01 has no exact binary floating point representation and a double turns exact price arithmetic into approximate comparisons. The value 0.1 in double is 0.1000000000000000055511151231257827, so adding 0.01 ten times does not give 0.1, and a test that a price equals a level fails on a value that is correct to the penny. Concretely, a limit order at 10.03 stored as a double may compare greater than a book level at 10.03 built by summing increments, so the order rests when it should cross or crosses when it should rest. Accumulating notional over a day compounds the error, and the profit and loss figure disagrees with the clearing statement by amounts that grow with volume. A 64-bit integer counting hundredths represents every quotable price exactly, compares with a single instruction, adds and subtracts exactly, and covers a range far beyond any real price. Multiplication and division still need care about rounding, and the scale must be chosen for the smallest increment the instrument can trade in, including sub-penny prices where they exist. The exchange itself publishes prices as integers with a stated exponent, so the wire format already tells you the intended representation, and converting it to a double at the parser discards information the exchange took care to give you.
Follow-up: You must compute a volume weighted average price across a million fills in ticks. How do you keep it exact without overflowing 64 bits?
Key concepts: floating point, fixed point, rounding error, price ticks.