Sympy - Float 没有属性 sqrt

Sympy - Float has no attribute sqrt

我正在编写一个代码片段,但我无法调试其中的问题,如有任何建议,我们将不胜感激。

错误是属性错误:Float对象没有属性sqrt

from sympy import *
import numpy as np

rho_l = 1000;
rho_g= 1.225;
sigma = 0.072
nu = 0.001;
Q = rho_g/ rho_l;
u = 14.8;

k = Symbol('k', real=True)
w1 = -2*nu*k**2
w2 = 4* (nu**2) * (k**4);
w3 = - Q* (u**2) * (k**2);
w4 = - sigma * (k**3)/ rho_l;
w = w1 + sqrt(w2+w3+w4);

print (w)
wprime = w.diff(k)
print (wprime)

ko = solve(wprime, k) # solve fprime = 0 with respect to x
ko = ko[0]
print (ko)

ws = lambdify (k, w, 'numpy');
print (type(ko))
print (ws(ko))

您收到该错误是因为 numpy 显然不知道如何处理 sympy.core.numbers.Float 类型 (https://docs.sympy.org/latest/modules/core.html#sympy.core.numbers.Float)。因此,当您调用 ws 时,numpy sqrt 会引发异常。要修复,请将 sympy 传递给 lambdify 而不是 numpy.

ws = lambdify (k, w, 'sympy');
print (type(ko)) # >> <class 'sympy.core.numbers.Float'>
print (ws(ko))   # >> -82.5885350883393

或者,您可以使用 float()sympy.Float 转换为常规浮点数,并将 k0 替换为 float(k0)

ws = lambdify(k, w, 'numpy');
print(type(float(ko)))  # >> <class 'float'>
print(ws(float(ko)))    # >> -82.58853508833931