First time here? Check out the FAQ!

Ask Your Question
1

How can I generate a Bitset with a fixed capacity and random bits?

asked 0 years ago

RMMM gravatar image

I'd like to generate Bitset objects with a capacity (length) of 10 bits for which the individual bits are chosen randomly.

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
1

answered 0 years ago

rburing gravatar image
sage: length = 10
sage: Bitset(f"{{:0{length}b}}".format(randint(0, 2**length - 1)))
0010101001
sage: Bitset(f"{{:0{length}b}}".format(randint(0, 2**length - 1)))
1100101000
Preview: (hide)
link

Comments

1

OK. Thanks.

But ... it's odd that Bitsets have to be constructed from strings.

RMMM gravatar imageRMMM ( 0 years ago )

I agree with you. The alternative is a list of integers. I would expect to be able to use a single integer (interpreted as its binary expansion). If you want you can open an issue on https://github.com/sagemath/sage/issues

rburing gravatar imagerburing ( 0 years ago )

Why not Bitset(ZZ(123).binary()) ?

Max Alekseyev gravatar imageMax Alekseyev ( 0 years ago )

Then you have to add zero padding, and the resulting code is slightly longer, though arguably a bit more readable. Feel free to add your own answer.

rburing gravatar imagerburing ( 0 years ago )
0

answered 0 years ago

Max Alekseyev gravatar image

A bitset of length L = 10 initialized with (bits of) a random integer:

L = 10
Bitset( ZZ(randint(2^L,2^(L+1)-1)).binary()[1:] )
Preview: (hide)
link

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 0 years ago

Seen: 264 times

Last updated: Aug 21 '24