Question

I'm calculating, say, NASDAQ, index.

All stocks prices are decimal I can make weight decimal or double - it doesn't matter.

nasdaq = weight1 * stock1 + weight2 * stock2 + .... + weightn * stockn.

As stock price is decimal it seems it makes sense to make nasdaq index decimal. But i do not want to recalculate nasdaq index every time some stock is updated. Instead I want to "cache" previous value and then only calculate difference. For example if stock2 is changed, then:

stock2OldPrice = stocks[2];
diff = stock2 - stock2OldPrice
nasdaq += diff * weight2     // need to synchronize
stocks[2] = stock2

Now I need to synchronize nasdaq index because stocks can be updated at the same time. For example I can receive in parallel threads new price for MSFT and INTC. So I have to write Interlocked.Add(ref nasdaq, diff * weight2); refer to my previous question how to synchronize addition from different threads using lock-free code? However I can not do that for decimal because decimals are not supported.

Ok, lets try to declare nasdaq index as double? With doubles I can do Interlocked.Add but now another problem: cause on every step I will convert from decimal to double I will lost precision. And then my "smart caching algorithm" will not absolutely "precise". It means that after 100 000 000 of updates value of my index become completely wrong I can't deal with that.

So it is not possible to use nor double neither decimal.

I do see only one possible solution - I have to declare nasdaq index as decimal so I can keep using my "smart caching algorithm" and so I have to use more complex "synchronization" mechanism, likely I have to use spinlocks.

Probably you can see simpler solution?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top