【问题标题】:only size-1 arrays can be converted to Python scalars - Python只有大小为 1 的数组可以转换为 Python 标量 - Python
【发布时间】:2023-01-14 15:10:52
【问题描述】:

我在尝试这段代码时出现错误:TypeError: only size-1 arrays can be converted to Python scalars。错误是由线路引起的

c1=(alp*bet-(alp*gam*(k-alp*bet*xi1))/(xi2-(alp*gam*xi1)))*((-lam2/lam1)*math.exp(lam1*x) + math.exp(lam2*x))

但我找不到问题所在。任何帮助表示赞赏。

import numpy as np
import matplotlib.pyplot as plt
import math

D=1  
k=0.001     
x0=0.5
L=1
s=0.01 
q=0.1  

lam1 =1/q + math.sqrt(1/q**2 + k/D)
lam2=1/q - math.sqrt(1/q**2 + k/D)

mu1=-1/q + math.sqrt(1/q**2 + k/D)
mu2=-1/q - math.sqrt(1/q**2 + k/D)

alp= 1/((-lam1)/(lam2))*math.exp(lam1*x0) + math.exp(lam2*x0)
bet=(s/(D*mu1))*math.exp(mu1*(x0-L))
gam= ((mu2)/(mu1))*math.exp((mu2-mu1)*L+mu1*x0)+math.exp(mu2*x0)
k=((s)/(D))*math.exp(mu1*(x0-L))
xi1=-lam2*math.exp(lam1*x0)+lam2*math.exp(lam2*x0)
xi2=mu2*math.exp((mu2-mu1)*L+mu1*x0)+mu2*math.exp(mu2*x0)
B=(k-(alp*bet*xi1))/(xi2-(alp*gam*xi1))


x = np.array([0, L, 10000])
c1=(alp*bet-(alp*gam*(k-alp*bet*xi1))/(xi2-(alp*gam*xi1)))*((-lam2/lam1)*math.exp(lam1*x) + math.exp(lam2*x))
c2=(k/mu1)-B*((mu2/mu1)*math.exp((mu2-mu1)*L+mu1*x)+math.exp(mu2*x))


c=np.piecewise(x, [x <= x0, x > x0], [c1, c2])
 

plt.plot(x,c)

【问题讨论】:

  • math.exp 参数应该是一个标量,类似于3lam1 * x在你的代码结果中是array([0.000000e+00, 2.000005e+01, 2.000005e+05])
  • 所以,改用np.exp,它接受一个数组并返回一个数组。

标签: python arrays numpy


【解决方案1】:

通常 Python 函数不能接受数组输入。如果将数组输入传递给函数,则会出现以下错误:只有大小为 1 的数组可以转换为 Python 标量 如何解决这个问题? 为了解决这个问题,我在函数内部使用了循环。请看下面的例子:

import numpy as np
# pass array in function
T = 300 # Kelvin
kb = 1.38E-23 #kelvin-1 mole-1
rho = 1000 # Kg/m3
P = 1 #Pressure - atm
cmd = np.linspace(10,90,100)
def muA(T): #  dynamic viscosity Pa - s
    muA=0.00001708*((T/273.15)**1.5)*((393.396)/(T + 120.246))
    return muA
#
def slipC(P,cmd0): #slipcorrection
    slipC0 = []
    for mdx, cmd0 in enumerate(cmd0):
        print(mdx,cmd0)
        slipC = 1 + (2/(P*pow(10,2)*cmd0*(10**-3)*0.752))*(6.32 + 2.01*math.exp(-0.1095*P*pow(10,2)*0.752*cmd0*pow(10,-3)))
        slipC0 = slipC0 + [slipC]
    return slipC0
print(cmd)
print(slipC(P,cmd))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-17
    • 2018-07-22
    • 2021-07-08
    • 1970-01-01
    • 2021-06-24
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多