Scale and shift an array of values so that they map to a specified target range [new_min, new_max]. This is Min-Max normalization to an arbitrary range.
import numpy as np
def shift_and_scale(arr: np.ndarray, new_min: float, new_max: float) -> np.ndarray:
old_min = np.min(arr)
old_max = np.max(arr)
if old_max == old_min:
return np.full_like(arr, (new_min + new_max) / 2.0, dtype=float)
# Normalize to [0, 1] then scale to [new_min, new_max]
normalized = (arr - old_min) / (old_max - old_min)
return normalized * (new_max - new_min) + new_min(new_max - new_min) and adding new_min.