Cycle using method in CoffeeScript - for-loop

Given I have two objects lower and upper of same type and they return successive value using method succ (as in ruby) and can be compared using <.
In plain javascript I can write:
for (var i = lower; i <= upper; i = i.succ()) {
// …
}
Using prototype I can write shorter:
$R(lower, upper).each(function(i){
// …
}, this)
Using prototype in coffeescript I can write even shorter:
$R(lower, upper).each (i)->
# …
, this
But without prototype, I found only this way to do same thing:
i = lower
while i <= upper
# …
i = i.succ()
Is there anything shorter?

I think you are correct that
i = lower
while i < upper
# …
i = i.succ()
is the shortest way to write this without using a function. Of course, you could write such a function without using Prototype:
eachSucc = (lower, upper, func) ->
i = lower
while i < upper
func i
i = i.succ()
Then you can call it like so:
eachSucc lower, upper, (i) -> ...

How about:
while upper >= n = i.succ()
alert n
Try it here, for the example I used the following fixture:
upper = 3
lower = 0
counter = (l) ->
_ = l
-> _++
i = succ: counter(lower)
/me still wishing for widespread generator support in Javascript..

Related

How to set my inequality constraint into my R function?

I am working on a project consisting of the analysis of different portfolio constructions in a universe of various assets. I work on 22 assets and I recalibrate my portfolio every 90 days. This is why a weights penalties (see code) constraint is applied as the allocation changes every period.
I am currently implementing a construction based on independent components. My objective is to minimize the modified value at risk based on its components. (See code below).
My function runs correctly and everything seems to be OK, my function "MVaR.IC.port" and "MVaR.cm" work well. However, I can only implement this model in the case where short selling is allowed. I would now like to operate only in "Long only", i.e. that my weight vectors w only contain elements >=0. Concretely, i want that the expression "w <- t(w.IC)%*%a$A" in my code be >=0.
Do you know how to help me? Thank you in advance.
[results w.out.MVaR.IC.22,][1] Here are the results that must be positive. I also constraint that the sum of the weights must be equal to 1 (the investor allocates 100% of his wealth.).
Thomas
PS: train and test represent my rolling windows. In fact, I calibrate my models on 'train' (in sample) and apply them on 'test' (out of sample) in order to analyse their performance.
########################################
######### MVar on IC with CM #########
########################################
lower = rep(-5,k)
upper = rep(5,k)
#Set up objective function and constraint
MVaR.IC.cm.port <- function(S, weights, alpha, MixingMatrix)
{
obj <- MVaR(S, weights, alpha)
w.ICA <- t(weights)%*%MixingMatrix
weight.penalty = abs(1000*(1-sum(w.ICA)))
down.weight.penalty = 1000*sum(w.ICA[w.ICA > 1])
up.weight.penalty = 1000*abs(sum(w.ICA[w.ICA < -1]))
return(obj + weight.penalty + down.weight.penalty + up.weight.penalty)
}
#Out of sample return portfolio computation
ret.out.MVaR.IC.cm.22 <- c()
w.out.MVaR.IC.cm.22 <- matrix(ncol = n, nrow = 10)
for (i in 0:9) {
train <- as.matrix(portfolioReturns.new[((1+i*90):(8*90+i*90)),])
test <- as.matrix(portfolioReturns.new[(1+8*90+i*90):(9*90+i*90),])
a <- myfastICA(train, k, alg.typ = "parallel", fun = "logcosh", alpha = 1,
method = "R", row.norm = FALSE, maxit = 2000,
tol = 0.0000000001, verbose = TRUE)
x <- DEoptim(MVaR.IC.cm.port,lower,upper,
control=list(NP=(10*k),F=0.8,CR=0.9, trace=50),
S=a$S, alpha = alpha, MixingMatrix = a$A)
w.IC <- matrix(x$optim$bestmem, ncol=1)
w <- t(w.IC)%*%a$A
for (j in 1:ncol(train)){
w.out.MVaR.IC.cm.22[(i+1),j] <- w[j]
}
ret.out.MVaR.IC.cm.22 <- rbind(ret.out.MVaR.IC.cm.22, test %*% t(w))
}
w.out.MVaR.IC.cm.22

F# Factorial function using while loop

i have gotten an assignment requesting the following:
Write a function
sum : n:int -> int
which uses the counter value, a local mutable value s, and a while-loop to compute the
sum 1+2+···+n as (2). If the function is called with any value smaller than 1, then it is
to return the value 0.
Now i know that you can make a recursive factorial script using match, but i can't quite put my finger as to how you can do the same using a while loop.
Any help is appreciated .
As this is an assignment question, I'm not going to answer by just giving the solution, but I think it will help you to see a brief snippet that shows all the constructs that you need to combine:
let imperativeDemo y = // Define a function taking 'y' as an argument
let mutable x = y // Create a mutable variable 'x' initialized to 'y'
while x < 20 do // Loop while 'x' is less than 20
x <- x + 1 // Mutate 'x' - increment it by one
x // Return the final value of 'x'
This function does not do anything useful, but it should be easy to adapt to implement the logic necessary for a factorial function.
This sums up the first n integers (that's not a factorial function!):
let sum n =
let mutable s = 0
let mutable counter = n
while counter > 0 do
s <- s + counter
counter <- counter - 1
s
For comparison, the tail-recursive version:
let sumRec n =
let rec sumRecInner n accu =
if (n <= 0) then accu else
sumRecInner (n - 1) (n + accu)
sumRecInner n 0

Converting Map[Int, Double] to breeze.linalg.SparseVector

I am new to the Breeze library and I would like to convert a Map[Int, Double] to breeze.linalg.SparseVector, and ideally without having to specify a fixed length of the SparseVector. I managed to achieve the goal with this clumsy code:
import breeze.linalg.{SparseVector => SBV}
val mySparseVector: SBV[Double] = new SBV[Double](Array.empty, Array.empty, 10000)
myMap foreach { e => mySparseVector(e._1) = e._2 }
Not only I have to specify a fixed length of 10,000, but the code runs in O(n), where n is the size of the map. Is there a better way?
You can use VectorBuilder. There's a (sadly) undocumented feature where if you tell it the length is -1, it will happily let you add things. You will have to (annoyingly) set the length before you construct the result...
val vb = new VectorBuilder(length = -1)
myMap foreach { e => vb.add(e._1, e._2) }
vb.length = myMap.keys.max + 1
vb.toSparseVector
(Your code is actually n^2 because SparseVector has to be sorted so you're repeatedly moving elements around in an array. VectorBuilder gives you n log n, which is the best you can do.)

Am I using a wrong numerical method?

This is the code:
f = dsolve('D3y+12*Dy+y = 0 ,y(2) = 1 ,Dy(2) = 1, D2y(2) = -1');
feval(symengine, 'numeric::solve',strcat(char(f),'=1'),'t=-4..16','AllRealRoots')
If I remove 'AllRealRoots' option it works fast and finds a solution, but when I enable the option Matlab does not finish for an hour. Am I using a wrong numerical method?
First, straight from the documentation for numeric::solve:
If eqs is a non-polynomial/non-rational equation or a set or list containing such an equation, then the equations and the appropriate optional arguments are passed to the numerical solver numeric::fsolve.
So, as your equation f is non-polynomial, you should probably call numeric::fsolve directly. However, even with the 'MultiSolutions' it fails to return more than one root over your range (A bug perhaps? – I'm using R2013b). A workaround is to call numeric::realroots to get bounds on each of the district real roots in your range and then solve for them separately:
f = dsolve('D3y+12*Dy+y = 0 ,y(2) = 1 ,Dy(2) = 1, D2y(2) = -1');
r = feval(symengine, 'numeric::realroots', f==1, 't = -4 .. 16');
num_roots = numel(r);
T = zeros(num_roots,1); % Wrap in sym or vpa for higher precision output
syms t;
for i = 1:num_roots
bnds = r(i);
ri = feval(symengine, '_range', bnds(1), bnds(2));
s = feval(symengine, 'numeric::fsolve', f==1, t==ri);
T(i) = feval(symengine, 'rhs', s(1));
end
The resultant solution vector, T, is double-precision (allocate it as sym or vpa you want higher precision):
T =
-0.663159371123072
0.034848320470578
0.999047064621451
2.000000000000000
2.695929753727520
3.933983894260340
4.405822476913172
5.868112290810963
6.108685019679461
You may be able to remove the for loop if you can figure out how to cleanly pass in the output of 'numeric::realroots' to 'numeric::fsolve' in one go (it's doable, but may require converting stuf to strings unless you're clever).
Another (possibly even faster) approach is to switch to using the numeric (floating-point) function fzero for the second half after you bound all of the roots:
f = dsolve('D3y+12*Dy+y = 0 ,y(2) = 1 ,Dy(2) = 1, D2y(2) = -1');
r = feval(symengine, 'numeric::realroots', f==1, 't = -4 .. 16');
num_roots = numel(r);
T = zeros(num_roots,1);
g = matlabFunction(f-1); % Create anonymous function from f
for i = 1:num_roots
bnds = double(r(i));
T(i) = fzero(g,bnds);
end
I checked and, for your problem here and using the default tolerances, the resultant T is within a few times machine epsilon (eps) of the numeric::fsolve' solution.

Algorithm for series

A, B, C,…. Z, AA, AB, ….AZ, BA,BB,…. , ZZ,AAA, …., write a function that takes a integer n and returns the string presentation. Can somebody tell me the algorithm to find the nth value in the series?
Treat those strings as numbers in base 26 with A=0. It's not quite an exact translation because in real base 26 A=AA=AAA=0, so you have to make some adjustments as necessary.
Here's a Java implementation:
static String convert(int n) {
int digits = 1;
for (int j = 26; j <= n; j *= 26) {
digits++;
n -= j;
}
String s = "";
for (; digits --> 0 ;) {
s = (char) ('A' + (n % 26)) + s;
n /= 26;
}
return s;
}
This converts 0=A, 26=AA, 702=AAA as required.
Without giving away too much (since this question seems to be a homework problem), what you're doing is close to the same as translating that integer n into base 26. Good luck!
If, as others suspect, this is homework, then this answer probably won't be much help. If this is for a real-world project though, it might make sense to do make a generator instead, which is an easy and idiomatic thing to do in some languages, such as Python. Something like this:
def letterPattern():
pattern = [0]
while True:
yield pattern
pattern[0] += 1
# iterate through all numbers in the list *except* the last one
for i in range(0,len(pattern)-1):
if pattern[i] == 26:
pattern[i] = 0
pattern[i+1] += 1
# now if the last number is 26, set it to zero, and append another zero to the end
if pattern[-1] == 26:
pattern[-1] = 0
pattern.append(0)
Except instead of yielding pattern itself you would reverse it, and map 0 to A, 1 to B, etc. then yield the string. I've run the code above and it seems to work, but I haven't tested it extensively at all.
I hope you'll find this readable enough to implement, even if you don't know Python. (For the Pythonistas out there, yes the "for i in range(...)" loop is ugly and unpythonic, but off the top of my head, I don't know any other way to do what I'm doing here)

Resources