[Python] rounding coordinates to centre of grid square

Discussão em 'Python' iniciado por Stack, Novembro 20, 2024.

  1. Stack

    Stack Membro Participativo

    Im currently trying to collect some weather data from an API, and to reduce the amount of API calls im trying to batch the calls on 0.5degree longitude and latitude chunks due to its resolution. I had this code

    def round_to_grid_center(coordinate,grid_spacing=0.5 ):
    offset = grid_spacing / 2
    return round(((coordinate - offset) / grid_spacing)) * grid_spacing + offset


    but this function rounded values at 0.5 down to 0.25 instead of up to 0.75, [​IMG] so i added this fix. It works for me, but I'm sure there is a better more efficient method to round the coordinates to their closest grid square centre. Please let me know!

    def round_to_grid_center(coordinate,grid_spacing=0.5 ):
    #temp fix for round down error
    if ((coordinate % 0.5)== 0 and (coordinate % 1 )!= 0):
    offset = grid_spacing / 2
    return round(((coordinate + 0.01 - offset) / grid_spacing)) * grid_spacing + offset
    else:
    offset = grid_spacing / 2
    return round(((coordinate - offset) / grid_spacing)) * grid_spacing + offset


    [​IMG]

    Continue reading...

Compartilhe esta Página