我想计算内部函数的积分
def H(x, z):
位于外部功能内
def integral_P_Vm(z):
有虚部的。以下是完整的代码:
from scipy.integrate import quad
import numpy as np
from scipy import interpolate
import quadpy
input="-0.5 0.0 \
-0.3 0.9 \
0.0 0.8 \
0.3 0.4 \
0.5 0.02"
input_coordinates = np.genfromtxt(input.splitlines()).reshape(-1,2) # shape to 2 columns, any number of rows
x_coordinates = input_coordinates[:,0]
H_values = input_coordinates[:,1]
H_interpolation = interpolate.InterpolatedUnivariateSpline(x_coordinates, H_values)
def k_x(z, M_r):
print("k_x(z, M_r)")
return (2)/(M_r(z))
def H(x, z):
print("H(x, z)")
print("X shape:", x.shape, "Current X", x)
print("Z shape", z.shape, "Current z:", z)
return H_interpolation(x)*np.exp(1j*k_x(z, M_r))#*x)
def f_D(x, z):
print("f_D")
return 1*np.exp(1j*x)*z
def M_r(z):
print("M_r")
return np.sqrt(z*z)
def psi_D(z):
print("psi_D")
return quadpy.quad(H, -0.5, 0.5, limit=50, args=[z])[0]
def integral_P_Vm(z):
print("Calling function")
return M_r(z)**2*np.exp(1j*psi_D(z))
Quadpy_integral = quadpy.quad(integral_P_Vm, 0, 1, limit=100)
print("Quadpy",Quadpy_integral)
但在这方面:
return H_interpolation(x)*np.exp(1j*k_x(z, M_r))
此代码给出以下错误:
Exception has occurred: ValueError
operands could not be broadcast together with shapes (42,) (21,)
这对我来说很奇怪,因为首先在x和z积分变量中有形状(21,): 输出:
X shape: (21,) Current X [-4.97828582e-01 -4.86953264e-01 -4.65078746e-01 -4.32531683e-01
-3.90408863e-01 -3.39704784e-01 -2.81378567e-01 -2.16697697e-01
-1.47196431e-01 -7.44371695e-02 1.11022302e-16 7.44371695e-02
1.47196431e-01 2.16697697e-01 2.81378567e-01 3.39704784e-01
3.90408863e-01 4.32531683e-01 4.65078746e-01 4.86953264e-01
4.97828582e-01]
Z shape (21,) Current z: [0.00217142 0.01304674 0.03492125 0.06746832 0.10959114 0.16029522
0.21862143 0.2833023 0.35280357 0.42556283 0.5 0.57443717
0.64719643 0.7166977 0.78137857 0.83970478 0.89040886 0.93253168
0.96507875 0.98695326 0.99782858]
但稍后在代码执行期间,x变量中有更多参数(42): 输出:
X shape: (42,) Current X [-0.49891429 -0.49347663 -0.48253937 -0.46626584 -0.44520443 -0.41985239
-0.39068928 -0.35834885 -0.32359822 -0.28721858 -0.25 -0.21278142
-0.17640178 -0.14165115 -0.10931072 -0.08014761 -0.05479557 -0.03373416
-0.01746063 -0.00652337 -0.00108571 0.00108571 0.00652337 0.01746063
0.03373416 0.05479557 0.08014761 0.10931072 0.14165115 0.17640178
0.21278142 0.25 0.28721858 0.32359822 0.35834885 0.39068928
0.41985239 0.44520443 0.46626584 0.48253937 0.49347663 0.49891429]
Z shape (21,) Current z: [0.00217142 0.01304674 0.03492125 0.06746832 0.10959114 0.16029522
0.21862143 0.2833023 0.35280357 0.42556283 0.5 0.57443717
0.64719643 0.7166977 0.78137857 0.83970478 0.89040886 0.93253168
0.96507875 0.98695326 0.99782858]
我不知道为什么X变量中的参数数量从(21,)变为(42,)。谁能解释一下为什么x变量中的参数数量从21变为42
因此,代码应该计算正确的积分
目前没有回答
相关问题 更多 >
编程相关推荐