【问题标题】:Python plotting a function with an integrationPython 绘制具有集成的函数
【发布时间】:2019-07-19 11:04:07
【问题描述】:

这是我正在使用的代码:

import matplotlib.pyplot as plt
from scipy import integrate
import numpy as np


def g(t):
    return integrate.quad(t, 0, t)


def f(t):
    return t ** 3 - g(t)


t1 = np.arange(-5, 5, 0.1)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1))
plt.show()

这里是我得到的错误信息:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

【问题讨论】:

    标签: python plot numerical-integration


    【解决方案1】:

    不用广播也可以这样。

    import numpy as np
    
    
    def g(t):
        g_value= integrate.quad (lambda t: t, 0, t)
        return (g_value)
    
    def f(t):
        f_value = t**3 - g(t)
        return (f_value)
    
    t1 = np.arange (-5, 5, 0.1)
    ft1 = []
    for tt in t1:
        ft1.append(f(tt)[0])
    
    plt.figure(1)
    plt.subplot(211)
    plt.plot(t1, ft1)
    plt.show()
    

    矢量化版本可以这样(mentioned here)

    import numpy as np
    def g(t):
        g_value= integrate.quad (lambda t: t ,0,t)
        return (g_value)
    
    g_vectorized = np.vectorize(g)
    
    def f(t):
        f_value = t**3 - g_vectorized(t)
        return (f_value)
    
    t1 = np.arange (-5, 5, 0.1)
    
    plt.figure(1)
    plt.subplot(211)
    plt.plot(t1, f(t1)[0])
    plt.show()
    

    它们都导致

    【讨论】:

    • 现在,它说:“ValueError: x 和 y 必须具有相同的第一维,但形状为 (100,) 和 (2, 100)”
    猜你喜欢
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多