簡體   English   中英

在c ++中組合兩個不同向量的比率

[英]Combine the ratios of two different vectors in c++

我不知道如何解釋,所以如果這個問題存在,請指出正確的主題。 我已經搜索了論壇,但找不到任何答案(也許我遺漏了數學或統計學中的關鍵字)。

如何從兩個向量生成具有組合權重的向量?

例如給定兩個向量:

vector_1 = {3, 3, 4}
vector_2 = {5, 5}

我們計算它們的權重,即元素除以向量中元素的總和。

weights_1 = {0.3, 0.3, 0.4}
weights_2 = {0.5, 0.5}

然后將它們組合以產生此向量。 組合權重是兩個向量的組合比率。

combined_weights = {0.3, 0.2, 0.1, 0.4}

有沒有可以計算組合權重的函數?

combined_weights = calculate(weights_1, weights_2)

過程是:

Step 1: combined_weights = {0.3} 

0.3 是 weights_1 的第一個元素。

Step 2: combined_weights = {0.3, 0.2, 0.1} 

0.2 和 0.1 之和是 weights_1 的第二個元素。 combine_weights 向量的總和等於 weights_2 的第一個元素。

Step 3: combined_weights = {0.3, 0.2, 0.1, 0.4} 

從combined_weights向量我們可以得到weights_1和weights_2,即

    weights_1 = {0.3, 0.2 + 0.1, 0.4}
    weights_2 = {0.3 + 0.2, 0.1 + 0.4}

我的目標是使 vector_1 和 vector_2 具有相似的大小。

new_vector_1 = {3, 2, 1, 4}
new_vector_2 = {3, 2, 1, 4}

在此處輸入圖片說明

更普遍,

在此處輸入圖片說明

您可以找到總數的LCM ,然后乘以,而不是將每個重量除以它的總數

int total1 = std::accumulate(weights1.begin(), weights1.end(), 0);
int total2 = std::accumulate(weights2.begin(), weights2.end(), 0);
int lcm = std::lcm(total1, total2);

我們想在下面做破壞性的事情,所以我們也可以對調整后的值這樣做

std::deque<int> working1;
std::transform(weights1.begin(), weights1.end(), std::back_inserter(working1), [=](int w){ return w * lcm / total1; });

std::deque<int> working2;
std::transform(weights2.begin(), weights2.end(), std::back_inserter(working2), [=](int w){ return w * lcm / total2; });

比較前面的元素,彈出較小的元素,將其添加到輸出(除非為零),然后將較大的元素遞減該值。 重復這個過程直到兩個副本都是空的

std::vector<int> combined;

while (!working1.empty() && !working2.empty())
{
    int & top1 = working1.front();
    int & top2 = working2.front();
    if (top1 < top2)
    {
        if (top1 > 0) { combined.push_back(top1) }
        top2 -= top1;
        working1.pop_front();
    }
    else
    {
        if (top2 > 0) { combined.push_back(top2) }
        top1 -= top2;
        working2.pop_front();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM