我目前正在嘗試創建一個體重指數計算器,它可以為您提供 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,
我怎樣才能使變數表示需要作為未知數獲得/損失的磅數,然后解決它。
uj5u.com熱心網友回復:
從技術上講,您要解決的不是方程式。這是一個不平等。也就是說,您可以通過分別處理兩種情況來使用不等式來解決此問題。
- 如果 BMI 高于 24,請計算降至 24 所需的體重,并給出此目標體重與實際體重之間的差異。
- 如果 BMI 低于 19,請計算達到 19 所需的體重,并給出此目標體重與實際體重之間的差異。
您似乎也誤解了求解功能的作業原理。給定一個運算式,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 求解函式。也就是說,以下腳本將導致相同的結果,但效率更高。
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: "))
uj5u.com熱心網友回復:
同情,真的嗎?
weight_pounds = bmi * height_inches**2 // 703
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/511298.html
標籤:Python变量同情
