英文:
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 :
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论