'Approximate equality test for polynomials.'

def almosteq(p1, p2, tolerance=None):

    ring = p1.ring
    if isinstance(p2, ring.dtype):
        if (set(p1.keys()) != set(p2.keys())):
            return False
        almosteq = ring.domain.almosteq
        for k in p1.keys():
            if (not almosteq(p1[k], p2[k], tolerance)):
                return False
        else:
            return True
    elif (len(p1) > 1):
        return False
    else:
        try:
            p2 = ring.domain.convert(p2)
        except CoercionFailed:
            return False
        else:
            return ring.domain.almosteq(p1.const(), p2, tolerance)
