绘制f(x,y,t)dt积分的3D图形问题

时间:2020-01-13 19:45:33

标签: python matplotlib plot spyder integral

我已经定义了函数I(a,b)=积分f(a,b,t)dt,并希望对其进行绘制以查看其如何取决于变量a和b。我首先编写了一个绘制y = I(k,x)的程序,并且工作得很好,但是我想看看它如何取决于两个变量,所以我尝试编写一个以3D绘制它的程序。

该程序适用于诸如三角函数和多项式之类的简单函数,但是当我尝试绘制I(x,y)时,它只是给我一个错误:“具有多个元素的数组的真值不明确。请使用a。 any()或a.all()”

这是代码,我最初编写了自己的程序来近似积分,但随后使用了scipy

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
import scipy.integrate as integrate

def integral(x,y):
    return integrate.quad(lambda t: np.sqrt((x**2 + y**2 - 2*x*y*np.cos(np.pi*t*(np.sqrt(1/x**3) - np.sqrt(1/y**3))))/(x**3*y**3)), 0,  np.sqrt(x**3*y**3))

X = np.arange(0.1,5,0.1)
Y = np.arange(0.1,5,0.1)
X,Y = np.meshgrid(X, Y)
Z = integral(X,Y)


fig = plt.figure()
ax = plt.axes(projection="3d")
ax.plot_wireframe(X, Y, Z, color='green')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')


ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
                cmap='winter', edgecolor='none')
ax.set_title('copper');

plt.show()
'''

1 个答案:

答案 0 :(得分:0)

scipy.integrate.quad返回一个元组。您只想要那个的第一个值。另外,您还需要对功能进行矢量化。

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import scipy.integrate as integrate

def integral(x,y):
    return integrate.quad(lambda t: np.sqrt((x**2 + y**2 - 2*x*y*np.cos(np.pi*t*(np.sqrt(1/x**3) - np.sqrt(1/y**3))))/(x**3*y**3)), 0,  np.sqrt(x**3*y**3))[0]

X = np.arange(0.1,5,0.1)
Y = np.arange(0.1,5,0.1)
X,Y = np.meshgrid(X, Y)
Z = np.vectorize(integral)(X,Y)

fig = plt.figure()
ax = plt.axes(projection="3d")
ax.plot_wireframe(X, Y, Z, color='green')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')


ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
                cmap='winter', norm=plt.Normalize(np.nanmin(Z), np.nanmax(Z)), edgecolor='none')

plt.show()

enter image description here