如何在不知道哪个较大的情况下找到两个值之间的差异? [英] How do I find the difference between two values without knowing which is larger?

查看:73
本文介绍了如何在不知道哪个较大的情况下找到两个值之间的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道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(xy )会完全满足您的要求:

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

这篇关于如何在不知道哪个较大的情况下找到两个值之间的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆