Simpson's Rule Integration Negative Area
The problem is how simpson works, it makes an estimate of the best possible quadratic function, with some data like yours, in which there is an almost vertical zone, the operation is wrong.
import numpy as np
from scipy.integrate import simps, trapz
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b, c):
return a + b * x + c * x ** 2
x = np.array([0.0, 99.0, 100.0, 299.0, 400.0, 600.0, 1700.0, 3299.0, 3300.0, 3399.0, 3400.0, 3599.0, 3699.0, 3900.0,
4000.0, 4300.0, 4400.0, 4900.0, 5000.0, 5100.0, 5300.0, 5500.0, 5700.0, 5900.0, 6100.0, 6300.0, 6600.0,
6900.0, 7200.0, 7600.0, 7799.0, 8000.0, 8400.0, 8900.0, 9400.0, 10000.0, 10600.0, 11300.0, 11699.0,
11700.0, 11799.0])
y = np.array([3399.68, 3399.68, 3309.76, 3309.76, 3274.95, 3234.34, 3203.88, 3203.88, 3843.5,
3843.5, 4893.57, 4893.57, 4893.57, 4847.16, 4764.49, 4867.46, 4921.13, 4886.32,
4761.59, 4731.13, 4689.07, 4649.91, 4610.75, 4578.84, 4545.48, 4515.02, 4475.86,
4438.15, 4403.34, 4364.18, 4364.18, 4327.92, 4291.66, 4258.31, 4226.4, 4188.69,
4152.43, 4120.52, 4120.52, 3747.77, 3747.77])
for i in range(3,len(x)):
popt, _ = curve_fit(func, x[i-3:i], y[i-3:i])
xnew = np.linspace(x[i-3], x[i-1], 100)
plt.plot(xnew, func(xnew, *popt), 'k-')
plt.plot(x, y)
plt.show()
Your samples have a very strong variation and x
are not equally spaced. Could it be something like
Runge's phenomenon?
trapz would be more accurate ?