How do I find the difference between two values without knowing which is larger?(如何在不知道哪个更大的情况下找到两个值之间的差异?)
问题描述
我想知道 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
这篇关于如何在不知道哪个更大的情况下找到两个值之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不知道哪个更大的情况下找到两个值之间的差异?


基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01