问题描述
我想知道 Python 中是否有一个函数可以确定两个有理数之间的距离,但我没有告诉它哪个数字更大.例如
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.
>>>distance(6,3)
3
>>>distance(3,6)
3
显然我可以写一个简单的定义来计算哪个更大,然后做一个简单的减法:
Obviously I could write a simple definition to calculate which is larger and then just do a simple subtraction:
def distance(x, y):
if x >= y:
result = x - y
else:
result = y - x
return result
但我宁愿不必调用这样的自定义函数.根据我有限的经验,我经常发现 Python 有一个内置函数或模块,可以完全按照您的意愿执行操作,并且比您的代码执行速度更快.希望有人能告诉我有一个内置函数可以做到这一点.
but I'd rather not have to call a custom function like this. From my limited experience I've often found Python has a built in function or a module that does exactly what you want and quicker than your code does it. Hopefully someone can tell me there is a built in function that can do this.
推荐答案
abs(x-y)
将完全满足您的需求:
abs(x-y)
will do exactly what you're looking for:
In [1]: abs(1-2)
Out[1]: 1
In [2]: abs(2-1)
Out[2]: 1
这篇关于如何在不知道哪个更大的情况下找到两个值之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!