Created
June 12, 2022 06:46
-
-
Save Liz4v/b927487cc9112a5de6a1ea928433541b to your computer and use it in GitHub Desktop.
Exponential Backoff Geometric Series Sum Ratio Calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Find Geometric Series Sum | |
This is free and unencumbered software released into the public domain. | |
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or | |
as a compiled binary, for any purpose, commercial or non-commercial, and by any means. | |
In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright | |
interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the | |
detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of | |
all present and future rights to this software under copyright law. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE | |
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE | |
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT | |
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
For more information, please refer to <https://unlicense.org> | |
--- end of license --- | |
I had to work with exponential backoff recently, and there is really no way to discuss a backoff ratio meaningfully. | |
You can only really say "it feels long, it feels short". However, it's far easier to discuss the remaining values in | |
the geometric series: initial wait, maximum wait, and number of attempts. I tried to symbolically derive a function | |
to calculate the ratio based on these parameters, unfortunately I have no idea. It looks log-like but other than that, | |
eh, I don't know. On the other hand, numerical approximation using derivatives seems to converge satisfatorily fast | |
(as initialization-time code, anyway). So this is what this code is. Shout out to sympy! | |
""" | |
import math | |
import typing as t | |
def exponential_backoff_times(initial: float, total: float, attempts: int) -> t.Generator[float, None, None]: | |
count = attempts - 1 | |
ratio = find_geometric_series_sum_ratio(total / initial, count) | |
yield from (initial * ratio**i for i in range(count)) | |
# After the last failed attempt, return the error message immediately. | |
yield 0.0 | |
def find_geometric_series_sum_ratio(target: float, count: int) -> float: | |
""" | |
Finds the ratio for a geometric series that will yield an expected finite sum. | |
It searches by iterating numerically, but it's very fast. | |
:param target: desired sum divided by initial value | |
:param count: the number of iterations in the sum to optimize for | |
""" | |
if target == count: | |
# Several zeroes pop up in the formulae in that particular case, and the answer is trivial anyway. | |
return 1.0 | |
working = None | |
ratio = 1.1 | |
seen = set() | |
while True: | |
try: | |
# Numerically optimized geometric series sum | |
working = math.expm1(math.log(ratio) * count) / (ratio - 1) | |
# I derived this formula using sympy. I cannot explain it beyond that it is numerical differentiation. | |
ratio += (target - working) * (ratio - 1) / (count * ratio ** (count - 1) - working) | |
except ValueError as e: | |
raise ValueError(f"r={ratio}, w={working}, t={target}, c={count}, s={seen}") from e | |
# Return on first dupe. Usually it's stable, but, in case of short loops, any loop item is pretty good. | |
if ratio in seen: | |
return ratio | |
seen.add(ratio) | |
def geometric_series_sum(initial: float, ratio: float, count: int) -> float: | |
try: | |
# This implementation has some numeric imprecisions for 0.99999999 < ratio < 1.00000001 but it's sympy-friendly. | |
return initial * (ratio**count - 1) / (ratio - 1) | |
except ZeroDivisionError: | |
return initial * count # Limit when ratio==1 | |
def main(): | |
import tempfile | |
filename = tempfile.mktemp(".factors.csv") | |
with open(filename, "w") as file: | |
for big in range(2, 200): | |
for small in range(2, big + 1): | |
file.write(str(find_geometric_series_sum_ratio(big, small))) | |
file.write(",") | |
file.write("\n") | |
print(f"Wrote to {filename}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment