I want a list x it contain 1 and -1, if rand(Binomial(1,0.5),1)[1] == 1 is true the value in that position of x is 1 and if it is not true then the value is -1 . i need to do this for 100 many times, so my length of x should be 100 How do i do that?? Sorry for the inconvenience.

Thanks for any advice or help.

Edit: deleting as the post question was rewritten and changed.

An easy way to do this is by scaling `rand()`

:

```
x = 2*rand(0:1, 100) .-1
```

1 Like

```
x = rand((-1, 1), 100)
```

?

3 Likes

BTW, this is needlessly complicated. You are creating a length-1 vector, and reading out the first element. It’s slow, too.

Instead, just directly generate a scalar value:

```
rand(Binomial(1,0.5))
```

Similarly, you can use `rand()`

, not `rand(1)[1]`

.

5 Likes

Thanks for your help. It is working now.

Generating rands from a range isn’t optimal. Here are some comparisons:

```
julia> @btime rand(0:1, 100);
656.522 ns (1 allocation: 896 bytes)
julia> @btime rand((0, 1), 100);
161.224 ns (1 allocation: 896 bytes)
julia> @btime rand(Bool, 100);
48.485 ns (1 allocation: 160 bytes)
```

So the fastes solution here uses something almost like your suggestion, @chiion. It has slightly more allocations than `rand((-1, 1), 100)`

:

```
(rand(Bool, 100) .* 2) .- 1
```

And don’t forget the similar:

```
(-1).^rand(Bool, 100)
```

which yields the same result but perhaps looks neater.

1 Like

ok. Thanks