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
这篇关于如何在不知道哪个更大的情况下找到两个值之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不知道哪个更大的情况下找到两个值之间的差异?


- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01