The following code is running correctly. However, when I call for the results one of the variables (utilizado) is returning incorrect values, only zeros. I know there is something I am making incorrectly but I don't know where.
using JuMP, Clp
m = Model(solver = ClpSolver())
#variable(m, utilizado[i=1:3] >= 0)
#variable(m, resultado[j=1:2] >= 0)
custo = [90, 120]
disponivel = [8, 6, 5]
matriz= [0.20 0.30;
0.20 0.25;
0.15 0.10]
#objective(m, Min, dot(custo, resultado))
#constraint(m, [i=1:3], sum(matriz[i,j] * resultado[j] for j=1:2) >=
disponivel[i])
print(m)
status = solve(m)
println("Objective value: ", getobjectivevalue(m))
println("Resultado: ", getvalue(resultado))
println("Resultado: ", getvalue(utilizado))
The final code was:
using JuMP, Clp
m = Model(solver = ClpSolver())
custo = [90, 120]
disponivel = [8, 6, 5]
matriz= [0.20 0.30;
0.20 0.25;
0.15 0.10]
#variable(m, utilizado[i=1:3] >= disponivel[i])
#variable(m, resultado[j=1:2] >= 0)
#objective(m, Min, dot(custo, resultado))
#constraint(m, [i=1:3], sum(matriz[i,j] * resultado[j] for j=1:2) == utilizado[i])
print(m)
status = solve(m)
println("Objective value: ", getobjectivevalue(m))
println("Resultado: ", getvalue(resultado))
println("Utilizado: ", getvalue(utilizado))
Related
I am trying to write a program (in Lua, but I guess this is more of a mathematical problem) that calculates the total distance between a set of numbers and there are two or three different possibilities for some of these numbers.
For example a set of numbers is: 2, 5, 0, 1. The sum of distances in this case is 9. (5-2 + 5-0 + 1-0)
The first row with alternatives is: 5, -, 3, 2.
The second row with alternatives is: 3, -, -, 3
The combination between the two rows with the smallest sum of distances is: 5, 5, 3, 3 with a sum of distances of 2.
My first attempt was to write a program that tries all possible iterations, but with a set of about 40 numbers, there are so many possibilities that my computer crashed...
Here is the code for that version, it first creates all the different possibilities and then calculates the differences and places them in column 0. Afterwards I can find the smallest value easily and see also the combination of numbers which results in that value.
local table1 = {2, 5, 0 ,1}
local table2 = {5, nil, 3, 2}
local imax = 1
local solution = {}
local answer = table1[1]
for x = 1,#table1 do
solution[x]={}
for i= 1, (2^imax)/2 do
solution[x][i] = table1[x]
end
if table2[x] ~= nil then -- there is an alternative number
for y = 1, x-1 do -- copy all the previous table entries except the last one
for j = ((2^imax)/2)+1, 2^imax do -- the number of new rows increases exponentially
solution[y][j] = solution[y][j-imax]
end
end
for j = ((2^imax)/2)+1, 2^imax do -- create the new table entry with the alternative number
solution[x][j] = table2[x]
end
imax = imax + 1 -- this number is to remind how many alternative numbers where found
end
end
solution[0]={}
for x = 1, #table1 do
for i = 1, (2^imax)/2 do
if x < #table1 then answer = math.sqrt((solution[x+1][i]-solution[x][i])^2) else answer = 0 end
if solution[0][i] == nil then solution[0][i] = answer else solution[0][i] = solution[0][i] + answer end
end
end
After reading about dynamic programming, I wrote a new version of this program. It calculates the smallest sum of differences, but I also want to know the path (the combination of numbers) to that sum... Still work to do...
local table1 = {2, 5, 0 ,1}
local table2 = {5, nil, 3, 2}
local solution = {}
local smallestsolution = {}
solution[1]={}
solution[2]={}
solution[3]={}
solution[4]={}
for i = 1, (#table1-1) do
solution[1][i] = math.sqrt((table1[i+1]-table1[i])^2)
if table2[i] ~= nil then solution[2][i] = math.sqrt((table1[i+1]-table2[i])^2) end
if table2[i+1] ~= nil then solution[3][i] = math.sqrt((table2[i+1]-table1[i])^2) end
if table2[i] ~= nil and table2[i+1] ~= nil then solution[4][i] = math.sqrt((table2[i+1]-table2[i])^2) end
end
for i = 1, (#table1-1) do
smallestsolution[i]=100000
for j = 1, 4 do
if solution[j][i] ~= nil and solution[j][i] < smallestsolution[i] then smallestsolution[i]=solution[j][i] end
end
end
local smallestsum = 0
for i = 1, (#table1-1) do
smallestsum = smallestsum + smallestsolution[i]
end
Thanks,
Emile
I managed to solve it myself! The hint to dynamic programming by #EgorSkriptunoff did the trick!
local table1 = {2, 5, 0 ,1}
local table2 = {5, nil, 3, 2}
local solution = {}
local smallestsolution = {}
solution[1]={}
solution[2]={}
solution[3]={}
solution[4]={}
local path = {}
local temp = {}
for i = 1, (#table1-1) do
solution[1][i] = math.sqrt((table1[i+1]-table1[i])^2)
if table2[i] ~= nil then solution[2][i] = math.sqrt((table1[i+1]-table2[i])^2) end
if table2[i+1] ~= nil then solution[3][i] = math.sqrt((table2[i+1]-table1[i])^2) end
if table2[i] ~= nil and table2[i+1] ~= nil then solution[4][i] = math.sqrt((table2[i+1]-table2[i])^2) end
end
for i = 1, (#table1-1) do
smallestsolution[i]=100000
temp[i] = 0
for j = 1, 4 do
if solution[j][i] ~= nil and solution[j][i] < smallestsolution[i] then smallestsolution[i]=solution[j][i] temp[i] = j end
end
end
local smallestsum = 0
for i = 1, (#table1-1) do
smallestsum = smallestsum + smallestsolution[i]
end
for i = 1, (#table1) do -- find the path belonging to the smallest sum of differences
if temp[i] == 1 then path[i] = table1[i] end
if temp[i] == 2 then path[i] = table2[i] end
if temp[i] == 3 then path[i] = table1[i] end
if temp[i] == 4 then path[i] = table2[i] end
if i == (#table1) then
if temp[i-1] == 1 then path[i] = table1[i] end
if temp[i-1] == 2 then path[i] = table1[i] end
if temp[i-1] == 3 then path[i] = table2[i] end
if temp[i-1] == 4 then path[i] = table2[i] end
end
end
I'm trying to understand what's going on with my calculation of canberra distance. I write my own simple canberra.distance function, however the results are not consistent with dist function. I added option na.rm = T to my function, to be able calculate the sum when there is zero denominator. From ?dist I understand that they use similar approach: Terms with zero numerator and denominator are omitted from the sum and treated as if the values were missing.
canberra.distance <- function(a, b){
sum( (abs(a - b)) / (abs(a) + abs(b)), na.rm = T )
}
a <- c(0, 1, 0, 0, 1)
b <- c(1, 0, 1, 0, 1)
canberra.distance(a, b)
> 3
# the result that I expected
dist(rbind(a, b), method = "canberra")
> 3.75
a <- c(0, 1, 0, 0)
b <- c(1, 0, 1, 0)
canberra.distance(a, b)
> 3
# the result that I expected
dist(rbind(a, b), method = "canberra")
> 4
a <- c(0, 1, 0)
b <- c(1, 0, 1)
canberra.distance(a, b)
> 3
dist(rbind(a, b), method = "canberra")
> 3
# now the results are the same
Pairs 0-0 and 1-1 seem to be problematic. In the first case (0-0) both numerator and denominator are equal to zero and this pair should be omitted. In the second case (1-1) numerator is 0 but denominator is not and the term is then also 0 and the sum should not change.
What am I missing here?
EDIT:
To be in line with R definition, function canberra.distance can be modified as follows:
canberra.distance <- function(a, b){
sum( abs(a - b) / abs(a + b), na.rm = T )
}
However, the results are the same as before.
This might shed some light on the difference. As far as I can see this is the actual code being run for computing the distance
static double R_canberra(double *x, int nr, int nc, int i1, int i2)
{
double dev, dist, sum, diff;
int count, j;
count = 0;
dist = 0;
for(j = 0 ; j < nc ; j++) {
if(both_non_NA(x[i1], x[i2])) {
sum = fabs(x[i1] + x[i2]);
diff = fabs(x[i1] - x[i2]);
if (sum > DBL_MIN || diff > DBL_MIN) {
dev = diff/sum;
if(!ISNAN(dev) ||
(!R_FINITE(diff) && diff == sum &&
/* use Inf = lim x -> oo */ (int) (dev = 1.))) {
dist += dev;
count++;
}
}
}
i1 += nr;
i2 += nr;
}
if(count == 0) return NA_REAL;
if(count != nc) dist /= ((double)count/nc);
return dist;
}
I think the culprit is this line
if(!ISNAN(dev) ||
(!R_FINITE(diff) && diff == sum &&
/* use Inf = lim x -> oo */ (int) (dev = 1.)))
which handles a special case and may not be documented.
the following error occurs. I tried to change the n .... but not working
"LoadError: BoundsError: attempt to access 9-element Array{Float64,1}:"
function bernstein_vandermonde( n )
if n == 1
v = ones(1, 1);
return v
end
v = zeros( n, n );
x = linspace( 0, 1, n );
for i = 1:n
println("entra no loop")
v[i,1:n] = bernstein_poly_01(n - 1, x[i])
end
return v
end
function bernstein_poly_01( n, x )
bern = ones(n)
if n == 0
bern[1] = 1
elseif 0 < n
bern[1] = 1 -x
bern[2] = x
for i = 2:n
bern[i+1] = x*bern[i];
for j = i-1:-1: 1
bern[j+1] = x*bern[j] + (1 - x)*bern[j+1]
end
bern[1] = (1 - x)*bern[1]
end
end
return bern
end
I can not solve :(
I'm an R novice with what I hope is a simple question. I've got a couple of nested loops I'm running and can't seem to get the output that I'm expecting.
I want to keep track of the balance in the internal loop. Each iteration represents 1 year. At the end of 15 years, I want to write the final balance to InvTotal for each of 4 simulations.
My final output should be 3 vectors (1 for each investment) of length 4, showing the final cumulative value for each investment at the end of 4 simulations.
My code is below. Any assistance you could provide would be a huge help.
Thank you!
Investment1_Balance <- 10000
Investment2_Balance <- 10000
Investment3_Balance <- 10000
Inv1Returns <- c(0, 1000, -500, 500)
Inv2Returns <- c(0, -9000, 30000, 10000)
Inv3Returns <- c(0, 4000, -1000, -2000)
Inv1Outcome = NULL
Inv2Outcome = NULL
Inv3Outcome = NULL
Inv1Total = NULL
Inv2Total = NULL
Inv3Total = NULL
random = NULL
for (j in 1:4)
{
for (i in 1:15 )
{
random[i] = runif(1, 0, 1)
Inv1Outcome[i] = if (random[i] <= .25){Investment1_Balance + Inv1Returns[1]}
else if (random[i] > .25 & random[i] <= .50){Investment1_Balance + Inv1Returns[2]}
else if (random[i] > .50 & random[i] <= .75){Investment1_Balance + Inv1Returns[3]}
else {Investment1_Balance + Inv1Returns[4]}
Inv2Outcome[i] = if (random[i] <= .20){Investment2_Balance + Inv2Returns[1]}
else if (random[i] > .20 & random[i] <= .30){Investment2_Balance + Inv2Returns[2]}
else if (random[i] > .30 & random[i] <= .70){Investment2_Balance + Inv2Returns[3]}
else ({Investment2_Balance + Inv2Returns[4]})
Inv3Outcome[i] = if (random[i] <= .50){Investment3_Balance + Inv3Returns[1]}
else if (random[i] > .50 & random[i] <= .70){Investment3_Balance + Inv3Returns[2]}
else if (random[i] > .70 & random[i] <= .90){Investment3_Balance + Inv3Returns[3]}
else ({Investment3_Balance + Inv3Returns[4]})
Investment1_Balance[i] =+ Inv1Outcome[i]
Investment2_Balance[i] =+ Inv2Outcome[i]
Investment3_Balance[i] =+ Inv3Outcome[i]
}
Inv1Total[j] = Investment1_Balance[15]
Inv2Total[j] = Investment2_Balance[15]
Inv3Total[j] = Investment3_Balance[15]
}
Inv1Total
Inv2Total
Inv3Total
Welcome to stackoverflow! There are a couple of points that you should consider while trying to figure out why your code isn't working as expected:
"Start small" : In your case here, I would start with one investment, maybe even with one simulation. This would verify if the logic of the calculation is fine, without distracting myself with other numbers.
"Seeing is believing" : Try to print intermediate results, so you can trace the calculation bugs.
Applying the previous, a first debugging would would look something like:
Investment1_Balance <- 10000
Inv1Returns <- c(0, 1000, -500, 500)
Inv1Outcome = NULL
Inv1Total = NULL
random = NULL
for (j in 1:4) { # Loop over simulations
cat("\n\n\nSimulation ", j, ": Investment balance:" , Investment1_Balance)
for (i in 1:15) { # Loop over years
random[i] = runif(1, 0, 1)
Inv1Outcome[i] = if (random[i] <= .25){Investment1_Balance + Inv1Returns[1]}
else if (random[i] > .25 & random[i] <= .50){Investment1_Balance + Inv1Returns[2]}
else if (random[i] > .50 & random[i] <= .75){Investment1_Balance + Inv1Returns[3]}
else {Investment1_Balance + Inv1Returns[4]}
Investment1_Balance[i] =+ Inv1Outcome[i]
cat("\n Year: ", i, "- Outcome:", Inv1Outcome[i], "- Final balance: " , Investment1_Balance[i])
}
Inv1Total[j] = Investment1_Balance[15]
}
Inv1Total
.
You can see a couple of problems with the numbers printed :
The outcome is always the same as the balance. This suggests that there might be a problem with the addition.
Let's try to debug that:
> x = 10
> x =+ 2
> x
[1] 2
Apparently, the =+ isn't working as expected. So we have to correct that : Investment1_Balance[i+1] = Investment1_Balance[i] + Inv1Outcome[i]
.
When printing the initial investment balance for each simulation, we can see that the first simulation is fine (Simulation 1 : Investment balance: 10000). But for the other simulations we get (Simulation 2 : Investment balance: 10000 9500 10000 10000 10500 11000 9500 11000 10000 10500 10500 10000 10000 11000 11000).
This suggests a problem with the initialization. Each simulation takes the output of the previous and starts with it. The logic of that is not quite correct. The simple solution would be resetting Investment1_Balance <- 10000 at the beginning of each simulation. It would even make sense in this case to reset all the Balance and Outcome variables.
.
Here is the new code after debugging :
Inv1Returns <- c(0, 1000, -500, 500)
random = NULL
Inv1Total = NULL
for (j in 1:4) { # Loop over simulations
Investment1_Balance <- 10000
Inv1Outcome = NULL
cat("\n\n\nSimulation ", j, ": Investment balance:" , Investment1_Balance)
for (i in 1:15) { # Loop over years
random[i] = runif(1, 0, 1)
Inv1Outcome[i] = if (random[i] <= .25){Investment1_Balance + Inv1Returns[1]}
else if (random[i] > .25 & random[i] <= .50){Investment1_Balance + Inv1Returns[2]}
else if (random[i] > .50 & random[i] <= .75){Investment1_Balance + Inv1Returns[3]}
else {Investment1_Balance + Inv1Returns[4]}
Investment1_Balance[i+1] = Investment1_Balance[i] + Inv1Outcome[i]
cat("\n Year: ", i, "- Outcome:", Inv1Outcome[i], "- Final balance: " , Investment1_Balance[i])
}
Inv1Total[j] = Investment1_Balance[15]
}
Inv1Total
Check if the output is now correct. If so, you can go ahead and add Inv2 and Inv3 as well.
I would like to write a function that has a loop in it which preforms the operations necessary for Euler's method. Below it my poor attempt.
In[15]:= Euler[icx_,icy_,h_,b_,diffeq_] :=
curx;
cury;
n=0;
curx = icx;
cury = icy;
While
[curx != b,
Print["" + n + " | " + curx + cury];
n++;
dq = StringReplace[diffeq, "y[x]" -> curx];
dq = StringReplace[dq, "x" -> cury];
curx+=h;
cury=cury+h*dq;
]
In[21]:= Euler[0, 0, .1, 1, e^-y[x]]
Out[21]= icx
To solve an ODE by Euler's method in Mathematica the code is:
Clear["Global`*"];
s = NDSolve[{y'[x] == Exp[-y[x]], y[0] == 0}, y, {x, 0, 1},
Method -> {"FixedStep", Method -> "ExplicitEuler"},
MaxSteps -> 20000];
Plot[Evaluate[y[x] /. s], {x, 0, 1}, PlotRange -> Full]
Otherwise, if you are dealing with homework, please state that on your tags.
HTH!
Here is an example of solution without any explicit loop.
If a loop is needed, I let you do it yourself.
EulerODE[f_ /; Head[f] == Function, {t0_, y0_}, t1_, n_] :=
Module[{h = (t1 - t0)/n // N, tt, yy},
tt[0] = t0; yy[0] = y0;
tt[k_ /; 0 < k < n] := tt[k] = tt[k - 1] + h;
yy[k_ /; 0 < k < n] :=
yy[k] = yy[k - 1] + h f[tt[k - 1], yy[k - 1]];
Table[{tt[k], yy[k]}, {k, 0, n - 1}]
];
ty = EulerODE[Function[{t, y}, y/t + y^2/t^2], {1, 1}, 2, 100] ;
Plot[Interpolation[ty][t], {t, 1, 2}]