I would like to sum a function (in my case f = np.exp(x))
inside of an equation. I’m not sure if I am right to think like that but I think I saw my teacher do something like this once. Any idea how that would work? Here is the code:
JavaScript
x
2
1
trc = (h2 / 2) * (f(x0) + (2 * (sum(f(i)) for i in xi)) + f(x8))
2
where f(i)
is my equation evaluated for every i in xi
(which is a list of float)
JavaScript
1
5
1
def f(x):
2
return np.exp(x)
3
4
xi = [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.825]
5
Advertisement
Answer
Numpy allows calculation of element-wise exponential for an array. Thus you could simply do:
JavaScript
1
2
1
trc = (h2/2)*(f(x0) + 2*sum(f(xi)) + f(x8))
2
You could also keep what you have written and modify it as follows:
JavaScript
1
2
1
trc = (h2/2)*((f(x0)) + 2*sum([f(i) for i in xi]) + (f(x8)))
2