I am creating an iterative algorithm (Monte Carlo method). The algorithm returns a value at each iteration, creating a stream of values.
I need to analyze these values and stop the algorithm when say 1000 return values with some epsilon .
I decided to implement its calculation of max and min values for the last 1000 values, and then calculate error using this formula (max-min)/min and compare it with epsilon : error<=epsilon , And if this condition is reached, stop the iteration and return result.
The first idea associated with the expression was to use the list and append values for it, calculating the max and min values for the last 1000 values after each addition.
Then I decided that to use more than 1000 last values. So I remembered deque . This was a very good idea, since the complexity of adding and removing at both ends of the deque is O(1) . But this did not solve the problem of having to go through all the last 1000 values at each iteration to calculate min and max .
Then I remembered that there is a heapq module. It stores data in such a way as to efficiently return the smallest of them at every moment. But I need both the smallest and the largest. In addition, I need to keep the order of the elements so that I can save the 1000 last returned elements of the algorithm, and I don’t see how this can be done with heapq .
Having all these thoughts, I decided to ask here:
How can I solve this problem most effectively?
source share