Sum function in SAS - sas

I am trying to create a small function to do the follow:
c = (a/3)*(1/((1+x)*2)+1/((1+x)*4)+1/((1+x)*8))+1/((1+x)*8)
Input variables are a and x. As you can see, the number to multiply by is a multiple of 2 (up to 8).
My main difficult is in the recursive sum. I know that SAS has a SUM function, but I am wondering how to use it in this exercise. I thought the parameter could be (1/((1+x)*n*2) (where n is a number).
Help is welcome. Thanks.

You can code a loop to iterate the pieces to accumulate. Something like:
data want;
a = 2;
x = 7;
steps = 4;
S = 0;
do index = 1 to steps;
S = sum (S, 1/(1+x)*index*2);
end;
c = a/3 * S;
run;

Related

Matlab's Accumarray equivalent in C++

I found a solution for matlab's accumarray equivalent in c++ with armadillo here. Although the code works like it should in matlab, my problem is that is takes a lot of time. It takes approximately 2.2 seconds to run and i have to call this function around 360 times. Is there a way to optimize this code or anyother way to implement accumarray in c++ with armadillo/opencv/boost? I know python has a bitcount function with numpy which is fast and efficient but i cant find anything in c++.
Thank You
EDIT
Currently I am using the following function, as it can be seen in the link attached
Code:
colvec TestProcessing::accumarray(icolvec cf, colvec T, double nf, int p)
{
/* ******* Description *******
here cf is the matrix of indices
T is the values whose data is to be
accumulted in the output array S.
if T is not given (or is scaler)then accumarray simply converts
to calculation of histogram of the input data
nf is the the size of output Array
nf >= max(cf)
so pass the argument accordingly
p is not used in the function
********************************/
colvec S; // output Array
S.set_size(int(nf)); // preallocate the output array
for(int i = 0 ; i < (int)nf ; i++)
{
// find the indices in cf corresponding to 1 to nf
// and store in unsigned integer array q1
uvec q1 = find(cf == (i+1));
vec q ;
double sum1 = 0 ;
if(!q1.is_empty())
{
q = T.elem(q1) ; // find the elements in T having indices in q1
// make sure q1 is not empty
sum1 = arma::sum(q); // calculate the sum and store in output array
S(i) = sum1;
}
// if q1 is empty array just put 0 at that particular location
else
{
S(i) = 0 ;
}
}
return S;
}
There is a C-version of accumarray for python.weave. It probably could get ported to plain C++ with some effort.
https://github.com/ml31415/numpy-groupies/blob/master/numpy_groupies/aggregate_weave.py

Do Loop for Matrix Multiplication in SAS

I have a 6*6 matrix called m1, and I want to use Do Loop in SAS to create matrices such that m2=m1*m1; m3=m2*m1; m4=m3*m1 ... mi=m(i-1)*m1.
Here is what I wrote:
proc iml;
use a;
read all into cat(m,1);
do i=2 to 10;
j=i-1;
cat(m,i)=cat(m,j)*cat(m,1);
print cat(m,i);
end;
quit;
And it won't work because cat(m,1) may not be correct. How can I use the Do Loop for this? Thank you very much for your time and help!
cat() is not going to work. It is a character function. It is not going to create a matrix named by the string output.
Why not just use the matrix power operator?
m2 = m1**2;
m3 = m1**3;
Unless you have big matrices, the time saved iterating the calculation instead of just using the power is next to 0.
For many iterative algorithms, you want to perform some computation on EACH matrix, but you don't need all matrices at the same time. For example, if you wanted to know the determinant of m, m##2, m##2, etc, you would write
result = j(10,1); /* store the 10 results */
m = I(nrow(a)); /* identity matrix */
do i = 1 to 10;
m = m*a; /* m is a##i during i_th iteration */
result[i] = det(m);
end;
print result;
If you actually need all 10 matrices at the same time in different matrices (this is rare), you can use the VALSET and VALUE functions as explained in this article: Indirect assignment: How to create and use matrices named x1, x2,..., xn
As an aside, you might also be interested in the trick of packing matries into an array by flattening them. It is sometimes a useful technique when you need to return k matrices from function module and k is a parameter to the module.

Populate the matrix proc iml SAS

I have a x matrix with two columns(c1,c2). I want to fix the first column (c1), add 10 columns each have values C2+m, C2+m...C2+m to the X matrix, m is a random integer. finally the matrix going to be:
C1, C2+m, C2+m, C2+m...C2+m;
CODE:
proc iml;
use nonpar;
read all var{treat response} into x;
do i=1 to 10;
call randseed(123);
call randgen(u, "Uniform");
Max = 300; Min = 68;
m = min + floor( (1+Max-Min)*u );
x = x[,1]||x[,2]+m;
end;
quit;
Can someone help me fix that..
Thanks
Couple of things that should lead you in the right direction.
First, pre-create your full destination matrix; don't concatenate constantly. So, once your read the dataset into x, make another x_new that is the same number of rows as x but has 11 columns. j will do this for you.
Second, you can make all of your random numbers at once, but you have to initially define the size of the matrix to fill, again using j. This is assuming you want a new random integer for each of the 10 columns AND each of the rows; if you want just each of the rows or just one 'm' in total you need to do this differently, but you need to clarify that. If you just want one row of 10 m's, then you can do that first (generate a u that has 10 columns 1 row) then expand that to the full number of rows of x using matrix multiplication.
Here's a simplified example using SASHELP.CLASS showing these two concepts at work.
proc iml;
use sashelp.class;
read all var {age weight} into x;
x_new = j(nrow(x),11); *making the new matrix with lots of columns;
x_new[,1] = x[,1]; *copy in column 1;
call randseed(123);
u = j(nrow(x),10); *make the to be filled random matrix;
call randgen(u,'Uniform',68,300); *the min/max parameters can go here;
u = floor(u+0.5); *as Rick noted in comments, needed to get the max value properly;
x_new[,2:11] = u[,1:10] + x[,2]; *populate x_new here;
print x_new;
quit;

Error when Calculating the Approximate Value of e^x [duplicate]

This question already has answers here:
Calculating e^x without using any functions
(4 answers)
Closed 8 years ago.
I am fairly new to c++ and writing a program to calculate the approximate value of e^x. Given by the formula:
1 + X + X^2/2! + ... + X^n/n! (for values of n from 1-100)
The program calculates the value perfectly until the user enters a number for "xValue" larger than 60 (ie. 61 or greater). I am unsure why this is and would really appreciate some feedback:
void calculate_sum(CalculateEx& numberSum)
{
double factoralSum;
numberSum.xTotal = numberSum.xValue;
numberSum.xTotal++;
for (double counter = 2; counter <= 100; counter++)
{
factoralSum = 1;
for (double factoral = 1; factoral <= counter; factoral++)
{
factoralSum *= factoral;
}
numberSum.xNextValue = pow(numberSum.xValue, counter) / factoralSum;
numberSum.xTotal += numberSum.xNextValue;
}
return;
}
Don't calculate the next row element from scratch, store the previous one, x^(n+1)/(n+1)! == (x^n)/n! * x/(n+1). This way you won't have to store values of x^n and especially n! separately (they are simply too big to fit in any reasonable type), whereas the values of x^n/n! converge to 0 as n rises.
Doing something like this would do:
double prevValue = 1;
sum = prevValue;
for (size_t power = 1; power < limit; ++power) {
prevValue *= x / (n + 1);
sum += prevValue;
}
Even a double can only fit so many digits. The computer always has a limit.
I know nothing about scientific computing, but I suppose if you wanted greater precision you might have to find a quad-precision floating point number or something.
Your program is attempting to calculate numbers that are out of the range of normal doubles. You can verify this by printing the value of factoralSum after the loop in which it is computed. If you insist on using the Taylor expansion, you may want to check the value of DBL_MAX in <float.h>
Java has a class called BigDecimal, which lets you create numbers with arbitrarily large precision. In C++, you may want to reference this question: Is there a C++ equivalent to Java's BigDecimal?

Known values for variables in a linear program written in Mathprog

I have a linear program written in MathProg. My unknown binary variable is a two-dimensional array defined as:
var x{i in V, l in L}, >=0, <=1;
where V and L are sets of integers.
The value of some variables, however, are known in advance and I would like to specify this for the solver in order to reduce the size of the ILP. For example I know that x[4,l] when l=2 is 1 and for any other values of l is zero. Currently, I specify this as as a constraint:
s.t. initial4{i in V: i=4}: sum{l in L}(l*x[i,l]) = 2;
I was wondering if this is the efficient way of specifying the values of a subset of unknowns in advance.
Ideally, I would like to place such information in a separate file together with the data section rather than in the model file.
Create an upper bound and lower bound for each variable:
var x{i in index_set}, >=x_L[i], <=x_U[i];
and adjust the lower and upper bounds for the known values.
Here is a MathProg snippet fixing x[2] to zero:
set index_set;
param x_L{index_set};
param x_U{index_set};
var x{i in index_set}, >=x_L[i], <=x_U[i];
s.t.
dummy:
sum{i in index_set} x[i] = 2;
solve;
display x;
data;
set index_set := 1, 2, 3;
param x_L default 0;
param x_U default 1 :=
2 0;
end;
From the (filtered) output it is clear that the preprocessor is smart enough to fix x[2] to 0:
glpsol --math test.mod
OPTIMAL SOLUTION FOUND BY LP PREPROCESSOR
x[1].val = 1
x[2].val = 0
x[3].val = 1