检查一个数字是否在另一个数字的百分之一范围内的Python代码。

huangapple go评论54阅读模式
英文:

Check if one number is within one percentage of another number in python

问题

Sure, here's the translated code portion:

我有2个数字

    a = 134
    b = 165

我想找出数字a比数字b少多少百分比我的目标是找出第一个数字a是否在第二个数字b的1%范围内
我创建了以下函数

    def is_what_percent_of(num_a, num_b):
        return (num_a / num_b) * 100

但这不是我想要的我想要检查给定的数字a是否在另一个数字b的1%范围内

例子

    a = 99.3
    b = 100
   
 
    在这种情况下数字a在数字b的1%范围内因此应返回True

是否有更简单的方法
英文:

I have 2 numbers.

a = 134
b = 165

I want to find out by what percentage number a is less than number b. My aim is to find if first number (a) is within 1% of second number (b).
I created function as follow

def is_what_percent_of(num_a, num_b):
    return (num_a / num_b) * 100

But it doesnt give me what I want. I want to check if given number (a) is within 1% of other number(b).

example

a = 99.3
b = 100


In this case, number a falls within 1% of number b and this it should return True.

Is there any easy way for this?

答案1

得分: 2

计算a和b的绝对值差所对应的百分比,并将其与1%进行比较:

如果 abs(a-b)/b <= 0.01 :
    ...

如果需要两种情况都适用(即两个数字中的任何一个与另一个在1%范围内),将两者中较大的数字作为分母:

如果 abs(a-b)/max(a,b) <= 0.01 :
    ...
英文:

Compute the percentage corresponding to the difference between a and b in absolute value and compare it to 1%:

if abs(a-b)/b <= 0.01 :
    ...

If you need it to work both ways (i.e. any of the two numbers is within 1% of the other), take the largest of the two as denominator:

if abs(a-b)/max(a,b) <= 0.01 :
    ...

huangapple
  • 本文由 发表于 2023年5月10日 19:36:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76217925.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定