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

前端 未结 11 2191
借酒劲吻你
借酒劲吻你 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:16

    This does not address the original question, but I thought I would expand on the answer zinturs gave. If you would like to determine the appropriately-signed distance between any two numbers, you could use a custom function like this:

    import math
    
    def distance(a, b):
        if (a == b):
            return 0
        elif (a < 0) and (b < 0) or (a > 0) and (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)
    
    print(distance(3,-5))  # -8
    
    print(distance(-3,5))  #  8
    
    print(distance(-3,-5)) #  2
    
    print(distance(5,3))   # -2
    
    print(distance(5,5))   #  0
    
    print(distance(-5,3))  #  8
    
    print(distance(5,-3))  # -8
    

    Please share simpler or more pythonic approaches, if you have one.

提交回复
热议问题