'Integration and interpolation in python
I have been trying to find a way to do this since days. I have an interpolated graph which I got from the following code:
for i in range(1,6):
u=np.linspace(0.0,2.6,num=i)
c=np.linspace(0.3, 1.0, num=i)
c_list = np.zeros(len(u))
for i in range(len(u)-1):
c = ((u[i+1]-u)*c[i]+(u-u[i])*c[i+1])/(u[i+1]-u[i])
print (c)
print (u)
plt.plot(u,c)
plt.show()
Now, I have two functions which I want to integrate using the obtained values. For that, I initially wrote:
n= lambda u:0.176*(np.exp(1/(u*c)))
integrate.quad(n, 0.0, 0.65)
But I keep running into type error no matter how I try to integrate this function. I am new to python and any help is appreciated.
edit: this is the error
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_85220/2767225254.py in <module>
15 print (e[1])
16 n= lambda u:(0.176*(np.exp(1/(u*c))))
---> 17 integrate.quad(n, 0.0, 2.6)
18
19 q= lambda n: n
~\anaconda3\lib\site-packages\scipy\integrate\quadpack.py in quad(func, a, b, args, full_output, epsabs, epsrel, limit, points, weight, wvar, wopts, maxp1, limlst)
349
350 if weight is None:
--> 351 retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
352 points)
353 else:
~\anaconda3\lib\site-packages\scipy\integrate\quadpack.py in _quad(func, a, b, args, full_output, epsabs, epsrel, limit, points)
461 if points is None:
462 if infbounds == 0:
--> 463 return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
464 else:
465 return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit)
TypeError: only size-1 arrays can be converted to Python scalars
Solution 1:[1]
I tested this one:
from scipy.integrate import quad_vec
import numpy as np
n= lambda u:0.176*(np.exp(1/(u*c)))
y, err = quad_vec(n, 0.0, 0.65)
# integrate.quad(n, 0.0, 0.65)
and y = array([nan, nan, nan, nan, inf]) and err = nan
Solution 2:[2]
I think the problem is the function n returning an array of values. This is because c is an array. You can see when c is a constant there is no issue. I think the function you should use is integrate.quad_vec().
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BarzanHayati |
| Solution 2 | KavG |

