【问题标题】:Problem plotting 3D graph of integral of f(x,y,t) dt绘制 f(x,y,t) dt 积分的 3D 图的问题
【发布时间】:2020-04-30 13:17:01
【问题描述】:

我已经定义了一个函数 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()
'''

【问题讨论】:

    标签: python matplotlib plot spyder integral


    【解决方案1】:

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

    【讨论】:

    • 所以我的原始代码(没有使用 scipy)的问题是我没有矢量化它?为什么我需要向量化这个函数而不是其他函数,例如 np.sin(x,y)?
    • Numpy 函数已经矢量化,即您可以计算 np.sin([1,2,3,4])。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2021-04-30
    • 2021-11-09
    相关资源
    最近更新 更多