I want to generate a matrix with random entries such that the determinant of that matrix is not zero using Maxima and further down the line implement this in STACK for Moodle. I am completely new to working with Maxima (or any CAS for that matter), so I have been going through various examples I found online and have so far managed to get this:
Generating a 2x2 random matrix with 0 or 1 (for simplicity reasons) and calculating its determinant:
g[i,j]:=1-random(2);
M1:genmatrix(g,2,2);
dM1:determinant(M1);
For the next step I wanted to define a matrix M2 as follows:
M2:(if dM1#0 then M1 else ***)
If the determinant of the matrix M1 is already not zero, fine, I'll go with that, but I am struggling with the else-part. I was thinking of creating a loop that generates new random numbers g[i,j] for M1 until I get a matrix with determinant not zero, but am unsure on how to do that or if there are other options.
In addition: as I mentioned this is ultimately something I want to implement in STACK for moodle (question will be to solve a system of linear equations with the generated matrix being the matrix of this system), so I don't know if there are any limitations on using if and while loops in STACK, so if somebody is aware of known problems I would appreciate any input.
You can say for ... do ... return(something) to yield something from the for-loop, which can be assigned to a variable. In this case it looks like this works as intended:
(%i9) M2: for i thru 10
do (genmatrix (lambda ([i, j], 1 - random(2)), 2, 2),
if determinant(%%) # 0 then return(%%));
[ 1 0 ]
(%o9) [ ]
[ 0 1 ]
(%i10) M2: for i thru 10
do (genmatrix (lambda ([i, j], 1 - random(2)), 2, 2),
if determinant(%%) # 0 then return(%%));
[ 1 0 ]
(%o10) [ ]
[ 1 1 ]
(%i11) M2: for i thru 10
do (genmatrix (lambda ([i, j], 1 - random(2)), 2, 2),
if determinant(%%) # 0 then return(%%));
[ 1 1 ]
(%o11) [ ]
[ 0 1 ]
Note that the first argument for genmatrix is a lambda expression (i.e. unnamed function). If you put the name of an array function such as g in your example, it will not have the intended effect, because in Maxima, array functions are memoizing functions, giving a stored output for an input that has been seen before. Obviously that's not intended if the output is supposed to be random.
Note also that M2 will be assigned done if the for-loop runs to completion without finding a non-singular matrix. I think that's useful, since you can see if M2 # 'done to ensure that you did get a result.
Finally note that it makes a difference to use the "group of expressions without local variables" (...) as the body of the for-loop, instead of "group of expressions with local variables" block(...), because the effect of return is different in those two cases.
Related
Given an array of integers which are needed to be split into four
boxes such that sum of XOR's of the boxes is maximum.
I/P -- [1,2,1,2,1,2]
O/P -- 9
Explanation: Box1--[1,2]
Box2--[1,2]
Box3--[1,2]
Box4--[]
I've tried using recursion but failed for larger test cases as the
Time Complexity is exponential. I'm expecting a solution using dynamic
programming.
def max_Xor(b1,b2,b3,b4,A,index,size):
if index == size:
return b1+b2+b3+b4
m=max(max_Xor(b1^A[index],b2,b3,b4,A,index+1,size),
max_Xor(b1,b2^A[index],b3,b4,A,index+1,size),
max_Xor(b1,b2,b3^A[index],b4,A,index+1,size),
max_Xor(b1,b2,b3,b4^A[index],A,index+1,size))
return m
def main():
print(max_Xor(0,0,0,0,A,0,len(A)))
Thanks in Advance!!
There are several things to speed up your algorithm:
Build in some start-up logic: it doesn't make sense to put anything into box 3 until boxes 1 & 2 are differentiated. In fact, you should generally have an order of precedence to keep you from repeating configurations in a different order.
Memoize your logic; this avoids repeating computations.
For large cases, take advantage of what value algebra exists.
This last item may turn out to be the biggest saving. For instance, if your longest numbers include several 5-bit and 4-bit numbers, it makes no sense to consider shorter numbers until you've placed those decently in the boxes, gaining maximum advantage for the leading bits. With only four boxes, you cannot have a num from 3-bit numbers that dominates a single misplaced 5-bit number.
Your goal is to place an odd number of 5-bit numbers into 3 or all 4 boxes; against this, check only whether this "pessimizes" bit 4 of the remaining numbers. For instance, given six 5-digit numbers (range 16-31) and a handful of small ones (0-7), your first consideration is to handle only combinations that partition the 5-digit numbers by (3, 1, 1, 1), as this leaves that valuable 5-bit turned on in each set.
With a more even mixture of values in your input, you'll also need to consider how to distribute the 4-bits for a similar "keep it odd" heuristic. Note that, as you work from largest to smallest, you need worry only about keeping it odd, and watching the following bit.
These techniques should let you prune your recursion enough to finish in time.
We can use Dynamic programming here to break the problem into smaller sets then store their result in a table. Then use already stored result to calculate answer for bigger set.
For example:
Input -- [1,2,1,2,1,2]
We need to divide the array consecutively into 4 boxed such that sum of XOR of all boxes is maximised.
Lets take your test case, break the problem into smaller sets and start solving for smaller set.
box = 1, num = [1,2,1,2,1,2]
ans = 1 3 2 0 1 3
Since we only have one box so all numbers will go into this box. We will store this answer into a table. Lets call the matrix as DP.
DP[1] = [1 3 2 0 1 3]
DP[i][j] stores answer for distributing 0-j numbers to i boxes.
now lets take the case where we have two boxes and we will take numbers one by one.
num = [1] since we only have one number it will go into the first box.
DP[1][0] = 1
Lets add another number.
num = [1 2]
now there can be two ways to put this new number into the box.
case 1: 2 will go to the First box. Since we already have answer
for both numbers in one box. we will just use that.
answer = DP[0][1] + 0 (Second box is empty)
case 2: 2 will go to second box.
answer = DP[0][0] + 2 (only 2 is present in the second box)
Maximum of the two cases will be stored in DP[1][1].
DP[1][1] = max(3+0, 1+2) = 3.
Now for num = [1 2 1].
Again for new number we have three cases.
box1 = [1 2 1], box2 = [], DP[0][2] + 0
box1 = [1 2], box2 = [1], DP[0][1] + 1
box1 = [1 ], box2 = [2 1], DP[0][0] + 2^1
Maximum of these three will be answer for DP[1][2].
Similarly we can find answer of num = [1 2 1 2 1 2] box = 4
1 3 2 0 1 3
1 3 4 6 5 3
1 3 4 6 7 9
1 3 4 6 7 9
Also note that a xor b xor a = b. you can use this property to get xor of a segment of an array in constant time as suggested in comments.
This way you can break the problem in smaller subset and use smaller set answer to compute for the bigger ones. Hope this helps. After understanding the concept you can go ahead and implement it with better time than exponential.
I would go bit by bit from the highest bit to the lowest bit. For every bit, try all combinations that distribute the still unused numbers that have that bit set so that an odd number of them is in each box, nothing else matters. Pick the best path overall. One issue that complicates this greedy method is that two boxes with a lower bit set can equal one box with the next higher bit set.
Alternatively, memoize the boxes state in your recursion as an ordered tuple.
I'm looking to a way to create a matrix filled with random values. Tried to create a matrix:make-constant, which, obviously, returns a constant (say, a matrix full of 6s). This answer doesn't seem to be working properly.
In my model, hunters should give random values to every patch in the world. They would then use this value to judge the opportunity to wait for game:
hunters-own [hunter-matrix]
to setup
clear-all
create-hunters number-hunters [
setxy random-xcor random-ycor
set hunter-matrix matrix:make-constant 33 33 random 10 ]
end
Is there a way to make the matrix filled with random numbers instead?
The answer you linked to is still correct, but it's using the old NetLogo 5 task syntax instead of the new -> syntax: https://ccl.northwestern.edu/netlogo/docs/programming.html#anonymous-procedures
The procedure still works as is:
to-report fill-matrix [n m generator]
report matrix:from-row-list n-values n [n-values m [runresult generator]]
end
However, you now call it using the -> syntax:
fill-matrix 33 33 [-> random 10]
I’m running a netlogo model with around 120000 turtles. At some point while the program is running, netlogo is changing one entry of a matrix to negative value. It is always happening at the same entry but the time and value differ. Normally nothing should be changed in this matrix and when I am running the program with a reduced Agentset, for example with 100000 turtles, everything works fine and the matrix is not changed.
Does anyone know why this is happening and probably has an answer to this issue?
Hi everyone,
This is the code snippet where the failure occurs:
set mxH2_seg1_tpa matrix:times-element-wise mx_seg1_tpa mxH1_av
set mxH2_seg1_tpb matrix:times-element-wise mx_seg1_tpb mxH1_av
set mxH2_r_seg1_tp matrix:times-element-wise mx_r_seg1_tp mxH1_av
set row 0
set column 0 ;At this point everything is fine
while [row <= 9][
while [column <= 24][
if matrix:get mxH2_seg1_tpa column row != 0 [matrix:set mxH_seg1_tpa column row (ln matrix:get mxH2_seg1_tpa column row)]
if matrix:get mxH2_seg1_tpb column row != 0 [matrix:set mxH_seg1_tpb column row (ln matrix:get mxH2_seg1_tpb column row)]
;After here matrix mx_r_seg1_tp is changed and partly filled with strange values
if matrix:get mxH2_r_seg1_tp column row != 0 [matrix:set mxH_r_seg1_tp column row (ln matrix:get mxH2_r_seg1_tp column row)]
set column column + 1]
set column 0
set row row + 1]
The complete code is already very long so if the mistake is somewhere there I need some advice what to look for.
Try setting the random seed (to any number). Then run your simulation and see when it fails and which turtle etc. Then run it again and stop it at the tick before failure and print out the variables and inspect the turtle that is about to cause the failure.
This line:
if matrix:get mxH2_r_seg1_tp column row != 0 [matrix:set mxH_r_seg1_tp column row (ln matrix:get mxH2_r_seg1_tp column row)]
sets an element of mxH_r_seg1_tp to the result of ln applied to an element of mxH2_r_seg1_tp. If you take the logarithm of a number less than 1 and greater than 0, the result will be a negative number. Is that what's happening? You can use #JenB's advice to check whether mxH2_r_seg1_tp has elements < 1 just before the failure.
Note that repeatedly taking the logarithm of the result of taking a logarithm will eventually produce a number less than 1. Perhaps it's also relevant that the first three lines of the posted code multiply matrix elements repeatedly, since repeated multiplication can generate numbers less than 1 as well. Or perhaps the multiplications cause the matrix elements to increase in magnitude, while taking the log decreases their magnitude, and it takes many ticks before any element is < 1? Since there are several matrices involved in repeated calculations, it's hard to know whether one of these factors might be relevant, but you will be able to check.
After reading through the complete code I found my mistake. At one specific point I forgot to use matrix:copy. I am still not sure how the size of the agentset is influencing this problem but I do not think it is some kind of implementation bug. Thank you very much for your support. Your tips helped me to find my mistake. So if anyone has a similar problem, check if matrix:copy was used appropriately. Cheers Jan
Just an update on Jan final answer: I encountered a similar issue with NetLogo 5.1 and the new updated Matrix module. It seems that matrix:times-scalar will not only report the resulting matrix, but will also tamper the original one. This can be demonstrated using this code snippet (enter in Command Center):
(let m matrix:from-row-list [[1 2 3] [4 5 6]]) (let m2 (matrix:times-scalar m -1)) (print m) (print m2)
Correct result (given by NetLogo 5.0.5) should be:
{{matrix: [ [ 1 2 3 ][ 4 5 6 ] ]}}
{{matrix: [ [ -1 -2 -3 ][ -4 -5 -6 ] ]}}
Wrong result (given by NetLogo 5.1 and 5.2RC3):
{{matrix: [ [ -1 -2 -3 ][ -4 -5 -6 ] ]}}
{{matrix: [ [ -1 -2 -3 ][ -4 -5 -6 ] ]}}
This is most probably a bug because matrix:times-scalar is defined as a reporter and not a procedure (ie: you cannot just do matrix:times-scalar m -1), and from the NetLogo documentation, reporter functions should report (return) their results without tampering the inputs.
Only matrix:times-scalar is affected. To workaround this issue, you can either use matrix:times (which supports scalars as input since NetLogo 5.1), or you can matrix:copy your matrix before using matrix:times-scalar, or you can use NetLogo 5.0.5 which is not affected by the issue (but new functions such as matrix:map won't be available).
For more info, see: https://github.com/NetLogo/Matrix-Extension/issues/12
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
how to get uniformed random between a, b by a known uniformed random function RANDOM(0,1)
In the book of Introduction to algorithms, there is an excise:
Describe an implementation of the procedure Random(a, b) that only makes calls to Random(0,1). What is the expected running time of your procedure, as a function of a and b? The probability of the result of Random(a,b) should be pure uniformly distributed, as Random(0,1)
For the Random function, the results are integers between a and b, inclusively. For e.g., Random(0,1) generates either 0 or 1; Random(a, b) generates a, a+1, a+2, ..., b
My solution is like this:
for i = 1 to b-a
r = a + Random(0,1)
return r
the running time is T=b-a
Is this correct? Are the results of my solutions uniformly distributed?
Thanks
What if my new solution is like this:
r = a
for i = 1 to b - a //including b-a
r += Random(0,1)
return r
If it is not correct, why r += Random(0,1) makes r not uniformly distributed?
Others have explained why your solution doesn't work. Here's the correct solution:
1) Find the smallest number, p, such that 2^p > b-a.
2) Perform the following algorithm:
r=0
for i = 1 to p
r = 2*r + Random(0,1)
3) If r is greater than b-a, go to step 2.
4) Your result is r+a
So let's try Random(1,3).
So b-a is 2.
2^1 = 2, so p will have to be 2 so that 2^p is greater than 2.
So we'll loop two times. Let's try all possible outputs:
00 -> r=0, 0 is not > 2, so we output 0+1 or 1.
01 -> r=1, 1 is not > 2, so we output 1+1 or 2.
10 -> r=2, 2 is not > 2, so we output 2+1 or 3.
11 -> r=3, 3 is > 2, so we repeat.
So 1/4 of the time, we output 1. 1/4 of the time we output 2. 1/4 of the time we output 3. And 1/4 of the time we have to repeat the algorithm a second time. Looks good.
Note that if you have to do this a lot, two optimizations are handy:
1) If you use the same range a lot, have a class that computes p once so you don't have to compute it each time.
2) Many CPUs have fast ways to perform step 1 that aren't exposed in high-level languages. For example, x86 CPUs have the BSR instruction.
No, it's not correct, that method will concentrate around (a+b)/2. It's a binomial distribution.
Are you sure that Random(0,1) produces integers? it would make more sense if it produced floating point values between 0 and 1. Then the solution would be an affine transformation, running time independent of a and b.
An idea I just had, in case it's about integer values: use bisection. At each step, you have a range low-high. If Random(0,1) returns 0, the next range is low-(low+high)/2, else (low+high)/2-high.
Details and complexity left to you, since it's homework.
That should create (approximately) a uniform distribution.
Edit: approximately is the important word there. Uniform if b-a+1 is a power of 2, not too far off if it's close, but not good enough generally. Ah, well it was a spontaneous idea, can't get them all right.
No, your solution isn't correct. This sum'll have binomial distribution.
However, you can generate a pure random sequence of 0, 1 and treat it as a binary number.
repeat
result = a
steps = ceiling(log(b - a))
for i = 0 to steps
result += (2 ^ i) * Random(0, 1)
until result <= b
KennyTM: my bad.
I read the other answers. For fun, here is another way to find the random number:
Allocate an array with b-a elements.
Set all the values to 1.
Iterate through the array. For each nonzero element, flip the coin, as it were. If it is came up 0, set the element to 0.
Whenever, after a complete iteration, you only have 1 element remaining, you have your random number: a+i where i is the index of the nonzero element (assuming we start indexing on 0). All numbers are then equally likely. (You would have to deal with the case where it's a tie, but I leave that as an exercise for you.)
This would have O(infinity) ... :)
On average, though, half the numbers would be eliminated, so it would have an average case running time of log_2 (b-a).
First of all I assume you are actually accumulating the result, not adding 0 or 1 to a on each step.
Using some probabilites you can prove that your solution is not uniformly distibuted. The chance that the resulting value r is (a+b)/2 is greatest. For instance if a is 0 and b is 7, the chance that you get a value 4 is (combination 4 of 7) divided by 2 raised to the power 7. The reason for that is that no matter which 4 out of the 7 values are 1 the result will still be 4.
The running time you estimate is correct.
Your solution's pseudocode should look like:
r=a
for i = 0 to b-a
r+=Random(0,1)
return r
As for uniform distribution, assuming that the random implementation this random number generator is based on is perfectly uniform the odds of getting 0 or 1 are 50%. Therefore getting the number you want is the result of that choice made over and over again.
So for a=1, b=5, there are 5 choices made.
The odds of getting 1 involves 5 decisions, all 0, the odds of that are 0.5^5 = 3.125%
The odds of getting 5 involves 5 decisions, all 1, the odds of that are 0.5^5 = 3.125%
As you can see from this, the distribution is not uniform -- the odds of any number should be 20%.
In the algorithm you created, it is really not equally distributed.
The result "r" will always be either "a" or "a+1". It will never go beyond that.
It should look something like this:
r=0;
for i=0 to b-a
r = a + r + Random(0,1)
return r;
By including "r" into your computation, you are including the "randomness" of all the previous "for" loop runs.
I'm trying to take the square root of a matrix. That is find the matrix B so B*B=A. None of the methods I've found around gives a working result.
First I found this formula on Wikipedia:
Set Y_0 = A and Z_0 = I then the iteration:
Y_{k+1} = .5*(Y_k + Z_k^{-1}),
Z_{k+1} = .5*(Z_k + Y_k^{-1}).
Then Y should converge to B.
However implementing the algorithm in python (using numpy for inverse matrices), gave me rubbish results:
>>> def denbev(Y,Z,n):
if n == 0: return Y,Z
return denbev(.5*(Y+Z**-1), .5*(Z+Y**-1), n-1)
>>> denbev(matrix('1,2;3,4'), matrix('1,0;0,1'), 3)[0]**2
matrix([[ 1.31969074, 1.85986159],
[ 2.78979239, 4.10948313]])
>>> denbev(matrix('1,2;3,4'), matrix('1,0;0,1'), 100)[0]**2
matrix([[ 1.44409972, 1.79685675],
[ 2.69528512, 4.13938485]])
As you can see, iterating 100 times, gives worse results than iterating three times, and none of the results get within a 40% error margin.
Then I tried the scipy sqrtm method, but that was even worse:
>>> scipy.linalg.sqrtm(matrix('1,2;3,4'))**2
array([[ 0.09090909+0.51425948j, 0.60606061-0.34283965j],
[ 1.36363636-0.77138922j, 3.09090909+0.51425948j]])
>>> scipy.linalg.sqrtm(matrix('1,2;3,4')**2)
array([[ 1.56669890+0.j, 1.74077656+0.j],
[ 2.61116484+0.j, 4.17786374+0.j]])
I don't know a lot about matrix square rooting, but I figure there must be algorithms that perform better than the above?
(1) the square root of the matrix [1,2;3,4] should give something complex, as the eigenvalues of that matrix are negative. SO your solution can't be correct to begin with.
(2) linalg.sqrtm returns an array, NOT a matrix. Hence, using * to multiply them is not a good idea. In your case, the solutions is thus correct, but you're not seeing it.
edit try the following, you'll see it's correct:
asmatrix(scipy.linalg.sqrtm(matrix('1,2;3,4')))**2
Your matrix [1 2; 3 4] isn't positive so there is no solution to the problem in the domain of real matrices.
What is the purpose of the matrix square root that you're doing? I suspect a practical application the matrix really could be symmetric positive definite (e.g. covariance) so you shouldn't encounter complex numbers.
In that case you can compute a cholesky decomposition, like a scaled LU factorization, see here: http://en.wikipedia.org/wiki/Cholesky_decomposition
Another practical example is if your matrices are rotations, then you can first decompose with matrix log and just divide by 2 in the log space, then go back to rotation with matrix exponent... in any event it sounds strange that you ask for a 'generic matrix square root', you probably want to understand the specific application in more depth.