# 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.

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

random() gives a number between 0 and 1

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

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?

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.

The values are indeed rounded, for instance:

(this time). As explained above:

`random()`

gives a random number in the interval $[0,1]$.`4*random()`

gives a random number in the interval $[0,4]$.`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:

Then

`diagonal_matrix( [ myrandom() for _ in range(8) ] )`

does the job.