使用 Python 集成常量函数
Integrate Constant function using Python
我正在用 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
包含0,所以velocity=time/time
包含0/0
作为第一项,也就是nan
然后integrate.cumtrapz
即可'计算积分。
您应该也看到了如下警告:
/usr/bin/ipython3:1: RuntimeWarning: invalid value encountered in true_divide
#! /bin/sh
警告您0/0
。
我正在用 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
包含0,所以velocity=time/time
包含0/0
作为第一项,也就是nan
然后integrate.cumtrapz
即可'计算积分。
您应该也看到了如下警告:
/usr/bin/ipython3:1: RuntimeWarning: invalid value encountered in true_divide
#! /bin/sh
警告您0/0
。