引入库
import scipy.optimize as opt
参数赋值
r = 0.1 # 球体半径m rho = 0.638 # 球体密度kg/m³ rho_w = 1000 # 水的密度kg/m³ s = rho / rho_w # 球体材料的比重 V_s = (4/3) * 3.1415926 * r3 # 球体体积 V_h = lambda h: (1/3)3.1415926(3rh2-h**3) # 球体高度为h部分的体积
定义目标函数
def object_func(h): return s * V_s - rho_w * (V_h(h) + V_s)
初始值和初始区间
x0 = 0.05 # 初始值 bounds = [(0, r)] # 初始区间
求解
result = opt.minimize_scalar(object_func, x0=x0, bounds=bounds, method='Bounded')
输出结果
print('球体浸入水中的质量为:', result.x*rho_w)