Search code examples
c++rquantitative-finance

Have R code snippet, Want to execute in C++


I have the following R code snippet from a technical paperthat I want to execute in a C++ program I am working on.

for(i in 1:m)
w[i] <- 1/sum(exp(L-L[i]))

I already have my vector L and from my understanding L-L[i] means the set of L[1]-L[i], L[2]-L[i] up to L[i]. To me this means:

w[0] = 1/sum(exp(L[0]-L[0]))
w[1] = 1/sum( c(exp(L[0]-L[1]),exp(L[1]-L[1]))  )

, etc.

I am unsure how to execute this in C++.


Solution

  • You can do something like this:

    #include <vector>
    #include <cmath>
    
    std::vector<double> func(const std::vector<double> &L)
    {
        std::vector<double> w;
        double sum;
        for (int i = 0, endi = L.size(); i < endi; ++i)
        {
            sum = 0.0;
            for (int j = 0, endj = i; j < endj; ++j)
            {
                sum += exp(L[j]-L[i]);
            }
            w.push_back(1.0/sum);
        }
        return w;
    }