Python绘制带有集成的函数

2024-04-25 08:24:00 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我使用的代码:

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

Tags: 代码fromimportnumpyreturnmatplotlibdefas
1条回答
网友
1楼 · 发布于 2024-04-25 08:24:00

不用广播就可以这样做

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

两者都会导致

enter image description here

相关问题 更多 >