简体   繁体   中英

Better way to do a sum of a function including two arrays between limits

I am trying to run a sum between 1 and k (which is 850 incidentally) the sum is the following;

I = sum( (e*I(l_i)*l_i/hc)*(l_i+1 - l_i ) 

where e, h and c are constants and l and I are arrays of equal length more than length k. The sum is over i which is the index of each array, running between 1 and k.

This is what I have so far;

import numpy as np
import scipy 
import scipy.constants 

e = scipy.constants.e
h = scipy.constants.h
c = scipy.constants.c

I = []

for i in range(1,k):
    I_temp = (e * Flux[i] * WaveL[i])/(h*c) * (WaveL[i+1]-WaveL[i])
    I.append(I_temp)

I_max = sum(I)

This works, but is there a quicker, more natural way to do this?

There are multiple optimization possibilities. I assume all vectors are Numpy objects.

  1. move e/(hc) out of the sum
  2. replace WaveL[i+1]-WaveL[i] by numpy.diff
  3. use numpy.dot to calculate the inner products of vectors (you'll need two calls)

Numpy is going to be much more efficient than the explicit loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM