def distance_pbc(p1, p2):
    """ Calculate distance respecting periodic boundary conditions. """
    total = 0
    try:
        coord_pairs = zip(p1, p2)
    except:
        coord_pairs = ((p1, p2),)
    for i, (a, b) in enumerate(coord_pairs):
        delta = abs(b - a)
        if delta > 1.0 - delta:
            delta = 1.0 - delta
        total += delta ** 2
    return total ** 0.5