简体   繁体   English

如何有效地计算向量上两个元素之间的总和

[英]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.我有一个数学问题,有人问我如何有效地将向量的几个元素的总和获取到 Python 程序中。

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).例如,我们有一个包含 n 个元素的向量 (v)(n=100000000,n 是一个随机实数),我们想要计算 v(10) 和 v(100000) 之间以及之后 v(8) 之间的总和和 v(100)。 In fact, we want to calculate efficiently the sum of elements between two elements A and B with (A < B).事实上,我们想要有效地计算两个元素 A 和 B 之间的元素之和 (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).解决方案是首先计算一个新向量 (w),它是向量 v 的累积和。 所以,如果我们想要 v(1) 和 v(1000) 之间的和,答案是 w(1000),如果我们想要 v(10) 和 v(1000) 之间的总和,答案将是 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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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