使用牛顿迭代法求解非线性方程
def f(h): r = 0.1 rho = 0.638 rho_w = 1.0 s = rho / rho_w Vh = (1.0 / 3) * (3 * r * h ** 2 - h ** 3) Vs = 4 / 3 * 3.14 * r ** 3 Vw = Vs - Vh return rho * g * Vs - rho_w * g * Vw
def f_derivative(h): r = 0.1 rho = 0.638 rho_w = 1.0 s = rho / rho_w return -g * (4 * 3.14 * r ** 3 * (2 * r - h) - 3 * (3 * r * h ** 2 - h ** 3)) * rho
g = 9.8 # 重力加速度 h = 0.05 # 初始值 epsilon = 1e-8 # 精度
while True: h_next = h - f(h) / f_derivative(h) if abs(h_next - h) < epsilon: break h = h_next
r = 0.1 rho = 0.638 Vs = 4 / 3 * 3.14 * r ** 3 Vh = (1.0 / 3) * (3 * r * h ** 2 - h ** 3) Vw = Vs - Vh m = Vw * 1000 # 水的密度为1000kg/m^3
print("球体浸入水中的质量为:{:.3f} kg".format(m))