Skip to content

Instantly share code, notes, and snippets.

@aleju
Last active February 2, 2023 19:46
Show Gist options
  • Select an option

  • Save aleju/eb75fa01a1d5d5a785cf to your computer and use it in GitHub Desktop.

Select an option

Save aleju/eb75fa01a1d5d5a785cf to your computer and use it in GitHub Desktop.

Revisions

  1. aleju revised this gist Feb 11, 2016. 1 changed file with 15 additions and 8 deletions.
    23 changes: 15 additions & 8 deletions quantize.py
    Original file line number Diff line number Diff line change
    @@ -1,12 +1,19 @@
    # Quantize a value with regards to a set of allowed values.
    #
    # Examples:
    # quantize(49.513, [0, 45, 90]) -> 45
    # quantize(43, [0, 10, 20, 30]) -> 30
    #
    # Note: function doesn't assume to_values to be sorted and
    # iterates over all values (i.e. is rather slow).
    def quantize(val, to_values):
    """Quantize a value with regards to a set of allowed values.
    Examples:
    quantize(49.513, [0, 45, 90]) -> 45
    quantize(43, [0, 10, 20, 30]) -> 30
    Note: function doesn't assume to_values to be sorted and
    iterates over all values (i.e. is rather slow).
    Args:
    val The value to quantize
    to_values The allowed values
    Returns:
    Closest value among allowed values.
    """
    best_match = None
    best_match_diff = None
    for other_val in to_values:
  2. aleju renamed this gist Feb 11, 2016. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. aleju created this gist Feb 11, 2016.
    17 changes: 17 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    # Quantize a value with regards to a set of allowed values.
    #
    # Examples:
    # quantize(49.513, [0, 45, 90]) -> 45
    # quantize(43, [0, 10, 20, 30]) -> 30
    #
    # Note: function doesn't assume to_values to be sorted and
    # iterates over all values (i.e. is rather slow).
    def quantize(val, to_values):
    best_match = None
    best_match_diff = None
    for other_val in to_values:
    diff = abs(other_val - val)
    if best_match is None or diff < best_match_diff:
    best_match = other_val
    best_match_diff = diff
    return best_match