def fit_bins_to_grid(hist_size, grid_size, grid_range):
    """
    Given a tentative number of bins `hist_size` for a histogram over
    the range `grid_range`, return a modified number of bins `hist_size`
    and a modified range `hist_range` so that the spacing of the histogram
    bins is an integer multiple (or integer divisor) of the grid spacing.

    Parameters:
    ----------
    hist_size: integer
        The number of bins in the histogram along the considered direction

    grid_size: integer
        The number of cells in the grid

    grid_range: list of floats (in)
        The extent of the grid

    Returns:
    --------
    hist_size: integer
        The new number of bins

    hist_range: list of floats
        The new range of the histogram
    """
    hist_range = grid_range
    hist_spacing = (hist_range[1] - hist_range[0]) * 1.0 / hist_size
    grid_spacing = (grid_range[1] - grid_range[0]) * 1.0 / grid_size
    if hist_spacing >= grid_spacing:
        hist_spacing = int(hist_spacing / grid_spacing) * grid_spacing
    else:
        hist_spacing = grid_spacing / int(grid_spacing / hist_spacing)
    hist_size = int((hist_range[1] - hist_range[0]) / hist_spacing)
    hist_range[1] = hist_range[0] + hist_size * hist_spacing
    return hist_size, hist_range
