Guest User

Untitled

a guest
Jul 22nd, 2022
503
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1.  
  2.  
  3. from random import randint, random
  4. stream = [randint(1000, 2000) for _ in range(20000)]
  5.  
  6. # The frugal streaming algorithm.
  7. # Based on https://agkn.wordpress.com/2013/09/16/sketch-of-the-day-frugal-streaming/
  8. # Originally presented in https://arxiv.org/pdf/1407.1121.pdf
  9. # The simplest version is called Frugal-1U. It converges a bit slow, but given a long enough stream it works well.
  10. # The Frugal-2U version modifies the step size along the way, plus other optimizations (not implemented here).
  11.  
  12. # Frugal streaming median finder.
  13. median_est = 0
  14. for x in stream:
  15.     if median_est < x:
  16.         median_est += 1
  17.     elif median_est > x:
  18.         median_est -= 1
  19.  
  20. # Frugal streaming 75th percentile finder.
  21. p75_est = 0
  22. for x in stream:
  23.     r = random()
  24.     if p75_est < x and r > 1 - 0.75:
  25.         p75_est += 1
  26.     elif p75_est > x and r > 0.75:
  27.         p75_est -= 1
  28.  
  29. # Test.
  30. stream.sort()
  31. actual = stream[len(stream) // 2]
  32. print("median actual={}, estimate={}".format(actual, median_est))
  33. actual = stream[int(len(stream)*0.75)]
  34. print("p75 actual={}, estimate={}".format(actual, p75_est))
Advertisement
Add Comment
Please, Sign In to add comment