How do I find the difference between two values without knowing which is larger?

前端 未结 11 2209
借酒劲吻你
借酒劲吻你 2020-12-11 14:22

I was wondering if there was a function built into Python that can determine the distance between two rational numbers but without me telling it which number is larger. e.g.

11条回答
  •  爱一瞬间的悲伤
    2020-12-11 15:18

    If you plan to use the signed distance calculation snippet posted by phi (like I did) and your b might have value 0, you probably want to fix the code as described below:

    import math
    
    def distance(a, b):
        if (a == b):
            return 0
        elif (a < 0) and (b < 0) or (a > 0) and (b >= 0): # fix: b >= 0 to cover case b == 0
            if (a < b):
                return (abs(abs(a) - abs(b)))
            else:
                return -(abs(abs(a) - abs(b)))
        else:
            return math.copysign((abs(a) + abs(b)),b)
    

    The original snippet does not work correctly regarding sign when a > 0 and b == 0.

提交回复
热议问题