Skip to content
Advertisement

for loop only for a certain part of an equation in python

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:

trc = (h2 / 2) * (f(x0) + (2 * (sum(f(i)) for i in xi)) + f(x8))

where f(i) is my equation evaluated for every i in xi (which is a list of float)

def f(x):
    return np.exp(x)

xi = [0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.825]

Advertisement

Answer

Numpy allows calculation of element-wise exponential for an array. Thus you could simply do:

trc = (h2/2)*(f(x0) + 2*sum(f(xi)) + f(x8))

You could also keep what you have written and modify it as follows:

trc = (h2/2)*((f(x0)) + 2*sum([f(i) for i in xi]) + (f(x8)))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement