Multiplication array with coefficient TypeError: only size-1 arrays can be converted to Python scalars

Multiplication array with coefficient TypeError: only size-1 arrays can be converted to Python scalars

我尝试将数组 D_0 与一些系数相乘以获得另一个数组 f_0 但我得到: 只有大小为 1 的数组可以转换为 Python 标量,为什么? 为什么我可以将参数 Re 作为向量,尽管我没有初始化它。我也尝试过 f_0 没有循环,但我得到了同样的错误。

代码: 导入数学 将 numpy 导入为 np

V_dot = np.array([[3, 1, 2, 1]])
rho_air = 1.2
L  = np.array([[10 ,8, 10, 8]])
mu = 1.8*10**-5
delta_P = 1
v_air = np.array([[5 ,3, 5, 3]])
epsilon = 0.2/1000 
m_dot = V_dot * rho_air
D_0 = (4*m_dot/(math.pi*rho_air*v_air))**(1/2)
D_1 = D_0
Re  = (v_air * D_0 * rho_air) / mu
print("Re", Re)
f_0= 0*D_0
for i in range(0, len(D_0)): 
    f_0 = (-2*math.log((epsilon/D_0[i])/3.7065))**-2
print('f_0', f_0,)

回复[[291346.24815789 130294.00317411 237883.21548704 130294.00317411]]

问题是math.log只能处理标量,你要用的是numpy库的log函数,它可以按元素应用于数组。将math.log改为np.log如下:

import numpy as np
import math

V_dot = np.array([[3, 1, 2, 1]])
rho_air = 1.2
L  = np.array([[10 ,8, 10, 8]])
mu = 1.8*10**-5
delta_P = 1
v_air = np.array([[5 ,3, 5, 3]])
epsilon = 0.2/1000 
m_dot = V_dot * rho_air
D_0 = (4*m_dot/(math.pi*rho_air*v_air))**(1/2)
D_1 = D_0
Re  = (v_air * D_0 * rho_air) / mu
print("Re", Re)
f_0= 0*D_0
for i in range(0, len(D_0)): 
    f_0 = (-2*np.log((epsilon/D_0[i])/3.7065))**-2
print('f_0', f_0,)

对于这个新问题,你可以通过做两件事来解决它。第一件事是创建一个 numpy 数组而不是列表。第二件事,你应该把all(e)改成e.all(),请参考下面的documentation。您可以在以下代码中找到这些更正:

import numpy as np

V_dot = np.array([[3, 1, 2, 1]])
rho_air = 1.2
L  = np.array([[10 ,8, 10, 8]])
mu = 1.8*10**-5
delta_P = 1
v_air = np.array([[5 ,3, 5, 3]])
epsilon = 0.2/1000 
m_dot = V_dot * rho_air
D_0 = (4*m_dot/(math.pi*rho_air*v_air))**(1/2)
D_1 = D_0
Re  = (v_air * D_0 * rho_air) / mu
print("Re", Re)
f_0 = (-2*np.log((epsilon/D_0)/3.7065))**-2
print('f_0', f_0,)
delta_P_tot = delta_P*L
f_1 = f_0
f_2 = 0
e   = np.ones(len(D_0))
while e.all() > 0.0001:
    D_1 = ((f_1 * L)/delta_P_tot )* rho_air * (v_air)**2
    print('D_1', D_1, '[m]')
    Re  = (v_air * D_1 * rho_air) / mu
    print('Re', Re, )
    f_2=(-2*np.log((epsilon/D_1)/3.7065 + 
    2.5226/(Re*np.sqrt(f_1))))**-2
    print('f_2', f_2,)
    e = abs(f_1-f_2)
    print('e', e, )
    f_1 = f_2