I'm creating an iterative algorithm (Monte Carlo method). The algorithm returns a value on every iteration, creating a stream of values.
I need to analyze these values and stop the algorithm when say 1000 returned values are withing some epsilon.
I decided to implement it calculation the max and min values of the last 1000 values, and then calculate the error using this formula (max-min)/min and compare it to epsilon: error<=epsilon. And if this condition is reached, stop the iterations and return the result.
The first hare-brained idea was to use a
listandappendnew values to it, calculating themaxandminvalues for the last1000values of it after each appending.Then I decided there is no use of keeping more that
1000last values. So I remembered ofdeque. It was a very good idea since the complexity on adding and deleting on both ends ofdequeobject isO(1). But it didn't solve the problem of needing to go through all the last 1000 values on each iteration to calculateminandmax.Then I remembered there is the
heapqmodule. It keeps the data in such a way as to efficiently return the smallest one at every moment. But I need both the smallest and the largest ones. Furthermore I need to preserve the order of the elements so that I can keep1000last returned elements of the algorithm, and I don't see how I can achieve it withheapq.
Having all those thoughts in mind I decided to ask here:
How can I solve this task the most efficiently?