pythonarraysloopsscalarvector-multiplication

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


I try to make a multiplication of an array D_0 with some coefficients for obtaining another array f_0 but I get: only size-1 arrays can be converted to Python scalars, why? Why can I have the paramerter Re as a vector althought I did not initialize it. I tried with f_0 as well without loop but I get the same error.

Code: import math 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= 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,)

Re [[291346.24815789 130294.00317411 237883.21548704 130294.00317411]]


Solution

  • The problem is that math.log can only deal with scalars, what you want to use is the log function of the numpy library, which can be applied element wise to the array. Change math.log by np.log as follows:

    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,)