[英]Solving for an unknown variable in python
我目前正在尝试创建一个体重指数计算器,它可以为您提供 BMI,然后计算保持健康体重所需的体重差异。
我用来计算 BMI 的公式是:
bmi = (weight_pounds / height_inches**2) * 703
使用 sympy,我试图找出在 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
我怎样才能使变量表示需要作为未知数获得/损失的磅数,然后解决它。
从技术上讲,您要解决的不是方程式。 这是一个不平等。 也就是说,您可以通过分别处理两种情况来使用不等式来解决此问题。
您似乎也误解了解决方案 function 的工作原理。 给定一个表达式, solve
寻找使表达式等于 0 的值。 要求解方程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")
但是,正如另一个答案(在我看来,粗鲁地)试图解释的那样,您也可以直接求解感兴趣的变量,而不是使用 sympy 求解 function。 也就是说,以下脚本将导致相同的结果,但效率更高。
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: "))
同情,真的吗?
weight_pounds = bmi * height_inches**2 // 703
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.