我目前正在尝试创建一个体重指数计算器,它可以为你提供BMI,然后计算达到健康体重所需的体重差异。
我用来计算BMI的方程式是:
bmi = (weight_pounds / height_inches**2) * 703
通过症状,我试图找出在19-24 BMI范围内需要增加或减少多少磅。
这就是我对这个方程的理解:
X = Symbol('X')
W = Symbol('W')
X = solve( W / height_inches**2) * 703
print(healthy_weight)
healthy_weight = X
当代码运行时,返回:
输入您的体重(磅(:160
输入你的身高(英寸(:66
你的BMI是:25.82,这意味着你超重了!
[0,0,0,0,0,0
我如何使一个变量将需要增加/减少的磅数表示为未知值,然后进行求解。
从技术上讲,你试图解决的不是一个方程;这是一个不平等。也就是说,你可以通过分别处理两个案例来使用不等式来解决这个问题。
- 如果BMI高于24,计算降到24所需的体重,并给出该目标体重与实际体重之间的差值
- 如果BMI低于19,计算达到19所需的体重,并给出该目标体重与实际体重之间的差值
您似乎也误解了solve函数的工作原理。给定一个表达式,solve
查找使该表达式等于零的值。要求解方程A = B
,可以经常使用solve(A - B, [variable to be solved])
。还要记住,solve
返回一个解决方案列表,即使该列表只包含一个元素。
因此,考虑以下代码。
import sympy as sp
height_inches = 72
weight_pounds = 200
W = sp.Symbol('W')
bmi = (weight_pounds / height_inches**2) * 703
if bmi > 24:
goal_weight = float(sp.solve((W/height_inches**2)*703 - 24, W)[0])
print("Weight loss required:")
print(weight_pounds - goal_weight)
elif bmi < 19:
goal_weight = float(sp.solve((W/height_inches**2)*703 - 19, W)[0])
print("Weight gain required:")
print(goal_weight - weight_pounds)
else:
print("Weight is in 'healthy' range")
然而,正如另一个答案(在我看来,粗鲁地(试图解释的那样,你也可以直接求解感兴趣的变量,而不是使用症状求解函数。也就是说,下面的脚本将导致相同的结果,但更有效。
height_inches = 72
weight_pounds = 200
W = sp.Symbol('W')
bmi = (weight_pounds / height_inches**2) * 703
if bmi > 24:
goal_weight = 24 * height_inches**2 / 703
print("Weight loss required:")
print(weight_pounds - goal_weight)
elif bmi < 19:
goal_weight = 19 * height_inches**2 / 703
print("Weight gain required:")
print(goal_weight - weight_pounds)
else:
print("Weight is in 'healthy' range")
如您在帖子中所示,为了提示用户输入,您可以将前两行代码替换为
height_inches = float(input("Enter your height in inches: "))
weight_pounds = float(input("Enter your weight in pounds: "))