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
list
andappend
new values to it, calculating themax
andmin
values for the last1000
values of it after each appending.Then I decided there is no use of keeping more that
1000
last values. So I remembered ofdeque
. It was a very good idea since the complexity on adding and deleting on both ends ofdeque
object isO(1)
. But it didn't solve the problem of needing to go through all the last 1000 values on each iteration to calculatemin
andmax
.Then I remembered there is the
heapq
module. 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 keep1000
last 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?