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

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

    abs function is definitely not what you need as it is not calculating the distance. Try abs (-25+15) to see that it's not working. A distance between the numbers is 40 but the output will be 10. Because it's doing the math and then removing "minus" in front. I am using this custom function:

    
    def distance(a, b):
        if (a < 0) and (b < 0) or (a > 0) and (b > 0):
            return abs( abs(a) - abs(b) )
        if (a < 0) and (b > 0) or (a > 0) and (b < 0):
            return abs( abs(a) + abs(b) )

    print distance(-25, -15) print distance(25, -15) print distance(-25, 15) print distance(25, 15)

提交回复
热议问题