【问题标题】:Integrate Constant function using Python使用 Python 集成常量函数
【发布时间】:2021-06-09 07:19:48
【问题描述】:

我正在使用 python 进行数值积分,它只是不适用于具有恒定值的数据,例如没有斜率。我知道解析积分是显而易见的,但我还是想知道为什么它在python中不起作用。

代码:

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

time = np.linspace(0, 10, num=20)
velocity = time/time

y_integral_numerical = integrate.cumtrapz(velocity, time, initial=0)
y_integral_analytical = time
print(y_integral_numerical)
plt.plot(time, velocity, 'ro',label="Velocity")
plt.plot(time, y_integral_numerical, 'g', label="Numerical Integral-Displacement")
#plt.plot(time, y_integral_analytical, 'b-', label="Analytical Integral-Displacement")

#plt.legend(loc="upper left")
plt.grid(True)
plt.legend()
plt.show()

【问题讨论】:

  • 您看到time/time 中关于除以0 的红色大警告了吗?下次你想要一个常量数组时,使用constant * np.ones(shape)

标签: python integration


【解决方案1】:

答案很简单:time 包含 0,所以velocity=time/time 包含0/0 作为第一个条目,即nan 然后integrate.cumtrapz 无法计算积分。

您还应该看到如下警告:

/usr/bin/ipython3:1: RuntimeWarning: invalid value encountered in true_divide
  #! /bin/sh

警告您注意0/0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 2013-10-09
    • 2019-07-09
    • 2021-09-19
    相关资源
    最近更新 更多