简体   繁体   中英

How to calculate efficiently the sum between two elements on a vector

I have a mathematic problem, someone asking me how to obtain efficiently the sum of several elements of a vector onto a program in python for example.

For example, we have a vector (v) with n elements (n=100000000 and n is a random real number) and we want to calculate the sum between v(10) and v(100000) and after, between v(8) and v(100). In fact, we want to calculate efficiently the sum of elements between two elements A and B with (A < B).

I'm not looking for an answer with directly a code. I'm looking for a mathematic explanation to understand this problem which is certainly a basic concept in vector efficient calculus.

The solution is to calculate in first a new vector (w) which is the cumulated sum of the vector v. So, if we want the sum between v(1) and v(1000), the answer is w(1000) and if we want the sum between v(10) and v(1000), the answer will be w(1000)-w(10-1). The only low calcul will be the cumulated sum.

The easiest way would be to build a memoisation table:

def sums(L):
    answer = {i:{j:0 for j in range(i,len(L))} for i in range(len(L))}
    for i,num in enumerate(L):
        answer[i][i] = L[i]
        for j in range(i+1, len(L)):
            answer[i][j] = answer[i][j-1] + L[j]

    return answer

Then query the table as follows:

table = sums(my_vector)
print(table[8][100])

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