Rounding entries of a random vector

Hello, I am trying to generate a random diagonal matrix, defined by a random vector over a field RR. The problem is that I need to round all the values to two decimal places, make entries evenly positive and negative (not necessary of equal amount) and, ideally, avoid zeroes. I have a code

[round(4*random()-2,2)for i in[1 .. 8]]

that produces a list of values that I need of size 8. However, I am struggling to combine it with a command diagonal_matrix and insert it there.

Also, I don't really understand why do we need to multiply it by 4 in here

[round(4*random()-2,2)for i in[1 .. 8]]

and why it produces negative values only, if I multiply it by 2 instead of 4. Could someone explain it please? Is there any other simpler and more elegant way to solve this problem? Thank you.

edit retag close merge delete

• diagonal_matrix(RR,[round(4*random()-2,2) for i in [1 .. 8]])

• random() gives a number between 0 and 1

( 2017-11-21 17:26:54 +0100 )edit

Thank you for your comment, but it seems that your suggestion doesn't work the way it should.

( 2017-11-21 18:04:04 +0100 )edit

Xenia, you should be more precise. Frédéric's solution does what you (seem to) ask; It returns a diagonal matrix with random elements rounded to two digits, with approx. as many positive elements as negative ones, and without zero with high probability. Where is the problem?

( 2017-11-21 18:09:29 +0100 )edit

The problem is, it is not rounded. Unfortunately, I do not get rounded result. And I would like to leave not diagonal entries as they are and get 0 there not 0.00 if it is possible. So, work only with a vector on a diagonal.

( 2017-11-21 18:40:08 +0100 )edit

The values are indeed rounded, for instance:

sage: [ round(4*random()-2,2) for i in[1 .. 8] ]
[-0.34, -1.03, 1.04, 0.75, -1.47, 1.05, -0.31, 1.78]


(this time). As explained above:

• random() gives a random number in the interval $[0,1]$.
• So 4*random() gives a random number in the interval $[0,4]$.
• So 4*random()-2 gives a random number in the interval $[0-2,4-2]=[-2,+2]$.

Yes, zero comes in the list with positive probability. A possibility to avoid zero is to use a "function in between" like:

sage: def myrandom():
....:     randy = round(4*random()-2,2)
....:     if randy:
....:         return randy
....:     return myrandom()

sage: myrandom()
-1.8


Then diagonal_matrix( [ myrandom() for _ in range(8) ] ) does the job.

( 2017-11-21 20:55:14 +0100 )edit