Reputation: 1346
What is a good way to sort an orderbook on price when the prices are floats/doubles? A binary tree works OK when the prices are integers because you can key off the price and get O(log(n)) add. It's a bad idea or at the very least risky to key off of floats/doubles.
Upvotes: 0
Views: 371
Reputation: 129454
First of all, I would suggest storing prices as integers. Just make the unit cents
, pence
, öre
or whatever the smaller unit is in your country - or even 1/1000th or 1/10000th of the main currency. This will save a lot of headache later on.
But as long as you are not making if (x.price == y.price)
, it's perfectly fine to use price
as a key. For sorting purposes, a binary tree only needs a less than
(or greater than
) comparison, which should be perfectly safe for floating point values. A value is always either smaller or bigger than some other value. It's only when you make calculations and try to determine if the value is precisely equal you get problems with floating point. [Or when you expect an exact result from calculations, such as multiplying by 2.46, then dividing by 2.46 and then subtracting the original number, and expecting exactly zero]
Upvotes: 5