I would like to implement the randomized rounding algorithm in Python.
The algorithm is quite easy to describe.
Given a vector, x, of size n where each element, x[i], of x is a real number between 0 and 1. Generate a 0-1 vector, y, of size n where each element of y, y[i], is either 0 or 1 as follows:
for i = 1 to len(x) do: set y[i] = 1 with probability x[i] and y[i] = 0 with probability 1 - x[i].
I tried to do this as follows but I guess I miss somethings or maybe there is quicker/better way:
import numpy
n = 4
x = [0.01, 0.6, 0.1, 0.7]
y = numpy.zeros(n)
for i in range(n):
randomNum = numpy.random.uniform()
if randomNum >= x[i]:
y[i] = 1
else:
y[i] = 0
Aucun commentaire:
Enregistrer un commentaire