【发布时间】: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参数应该是一个标量,类似于3。lam1 * x在你的代码结果中是array([0.000000e+00, 2.000005e+01, 2.000005e+05]) -
所以,改用
np.exp,它接受一个数组并返回一个数组。