Ask Your Question
1

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

asked 2024-08-20 06:22:21 +0100

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.

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
1

answered 2024-08-20 13:36:29 +0100

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
edit flag offensive delete link more

Comments

1

OK. Thanks.

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

RMMM gravatar imageRMMM ( 2024-08-20 18:11:36 +0100 )edit

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 ( 2024-08-20 19:08:53 +0100 )edit

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

Max Alekseyev gravatar imageMax Alekseyev ( 2024-08-21 03:13:30 +0100 )edit

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 ( 2024-08-21 08:33:17 +0100 )edit
0

answered 2024-08-21 17:11:21 +0100

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:] )
edit flag offensive delete link more

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: 2024-08-20 06:22:21 +0100

Seen: 247 times

Last updated: Aug 21