Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a array of random True/False

Here is what I am currently doing:

a = trues(100)
for i in 1:length(a)
   a[i] = rand()>0.5 ? true : false
end

Is there a better (faster) solution?

like image 827
Remi.b Avatar asked Feb 05 '15 21:02

Remi.b


2 Answers

In Julia 0.4 you can write bitrand(100):

julia> bitrand(100)
100-element BitArray{1}:
  true
  true
 false
 false
  true
     ⋮
  true
 false
  true
  true
  true

You can get this using the Compat package in older versions of Julia, or you can use the old name, randbool (same behavior, different name). Simon's answer of rand(Bool,100) works but it gives an Array{Bool} instead of a BitArray – a special data type that stores boolean arrays compactly using only a bit per boolean.

like image 177
StefanKarpinski Avatar answered Nov 15 '22 14:11

StefanKarpinski


I haven't benchmarked it but the fastest option seems likely to be:

a = rand(Bool,100,1)

... see the bottom of the Julia documentation page on Multi-dimensional Arrays.

like image 25
Simon Avatar answered Nov 15 '22 16:11

Simon