在 Python 中计算两个数字之间的百分比

您所在的位置:网站首页 两个数怎么求 在 Python 中计算两个数字之间的百分比

在 Python 中计算两个数字之间的百分比

#在 Python 中计算两个数字之间的百分比| 来源: 网络整理| 查看: 265

要计算两个数字之间的百分比,请将一个数字除以另一个数字,然后将结果乘以 100,例如 (30 / 75) * 100。这显示第一个数字占第二个数字的百分比。 在示例中,30 是 75 的 40%。

def is_what_percent_of(num_a, num_b): return (num_a / num_b) * 100 print(is_what_percent_of(30, 75)) # 👉️ 40.0 print(is_what_percent_of(20, 75)) # 👉️ 26.6666... print(round(is_what_percent_of(20, 75), 2)) # 👉️ 26.67 # -------------------------------------------------- def get_percentage_increase(num_a, num_b): return ((num_a - num_b) / num_b) * 100 print(get_percentage_increase(50, 30)) # 👉️ 66.6666... print(get_percentage_increase(50, 100)) # 👉️ -50.0 # -------------------------------------------------- def get_percentage_difference(num_a, num_b): # 👇️ use abs() function to always get positive number return (abs(num_a - num_b) / num_b) * 100 print(get_percentage_difference(50, 30)) # 👉️ 66.6666... print(get_percentage_difference(50, 100)) # 👉️ 50.0

Python 中计算两个数字之间的百分比

第一个函数接受 2 个数字并返回第一个数字占第二个数字的百分比。

例如,25 / 50 * 100 表示 25 是 50 的 50%。

print((25 / 50) * 100) # 👉️ 50.0

计算两个数字之间的百分比时,我们可能需要四舍五入到小数点后的特定位数。

round 函数采用以下 2 个参数:

number 要四舍五入到小数点后 ndigits 精度的数字ndigits 数字在操作后应具有的小数点后的位数(可选) print(round((23 / 43) * 100, 2)) # 👉️ 53.49

round 函数返回四舍五入到小数点后 ndigits 精度的数字。

如果省略 ndigits,函数返回最接近的整数。

第二个函数显示如何获得两个数字之间的百分比增加/减少。

def get_percentage_increase(num_a, num_b): return ((num_a - num_b) / num_b) * 100 print(get_percentage_increase(50, 30)) # 👉️ 66.6666... print(get_percentage_increase(50, 100)) # 👉️ -50.0

第一个示例显示从 30 增加到 50 的百分比是 66.6666...%。

第二个显示从 100 到 50 的百分比增加是 -50%。

如果你总是需要得到一个正数,使用 abs() 函数。

def get_percentage_increase(num_a, num_b): return (abs(num_a - num_b) / num_b) * 100 print(get_percentage_increase(50, 30)) # 👉️ 66.6666... print(get_percentage_increase(50, 100)) # 👉️ 50.0

abs 函数返回数字的绝对值。 换句话说,如果数字是正数,则返回数字,如果数字是负数,则返回数字的负数。这样,我们始终可以保证在计算两个数字之间的百分比差异时得到一个正数。

我们可能想要处理的事情是除以 0。除以 0 会在 Python 中引发 ZeroDivisionError。

def get_percentage_increase(num_a, num_b): return (abs(num_a - num_b) / num_b) * 100 print(get_percentage_increase(50, 0)) # 👉️ inf print(get_percentage_increase(50, 50)) # 👉️ 0.0 print(get_percentage_increase(50, 100)) # 👉️ 50.0

python ZeroDivisionError

我们可以在 try/except 块中处理错误。

def get_percentage_increase(num_a, num_b): try: return (abs(num_a - num_b) / num_b) * 100 except ZeroDivisionError: return float('inf') print(get_percentage_increase(50, 0)) # 👉️ inf print(get_percentage_increase(50, 50)) # 👉️ 0.0 print(get_percentage_increase(50, 100)) # 👉️ 50.0

如果我们收到 ZeroDivisionError 错误,我们将返回 Infinity,但是我们可以以适合您的用例的任何其他方式处理该错误。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3