2
$\begingroup$

I am working on a problem where I need to generate a list of random Boolean values. My current approach is to first generate a list of random integers (0 or 1), and then convert this list to a Boolean list. However, I am struggling to find an efficient way to perform this conversion.

My current method uses the Map function, but it's quite slow, especially when dealing with large lists. Here's my code:

Module[{v = RandomInteger[{0, 1}, 10000000]}, 
 AbsoluteTiming[# != 0 & /@ v]]

This operation takes around 1.96 seconds to run on my machine, which is too slow for my needs.

I am looking for a more efficient way to convert a large list of integers to a Boolean list. Any suggestions or improvements would be greatly appreciated.

$\endgroup$
6
  • 8
    $\begingroup$ AbsoluteTiming[v = RandomChoice[{False, True}, 10000000]] $\endgroup$
    – Syed
    Aug 15, 2023 at 1:54
  • $\begingroup$ @Syed Thank you! It's indeed much faster, takes 0.165785 seconds, while I find RandomInteger is even faster, takes 0.0229642 seconds. $\endgroup$
    – Tokubara
    Aug 15, 2023 at 2:06
  • 2
    $\begingroup$ I left it as a comment as your first sentence says: I need to generate a list of random Boolean values and it changes to I am looking for a more efficient way to convert a large list of integers to a Boolean list at the end. $\endgroup$
    – Syed
    Aug 15, 2023 at 2:15
  • 8
    $\begingroup$ If you are working with massive numbers of Booleans, maybe it'd be faster to change your code to take {0,1} instead of {False,True} since AbsoluteTiming[v = RandomInteger[{0, 1}, 10000000];] is about 2 times faster than AbsoluteTiming[v = RandomChoice[{True, False}, 10000000];] This may be irrelevant to your application though, as the main bottleneck in your code could be somewhere else $\endgroup$
    – ydd
    Aug 15, 2023 at 2:19
  • 1
    $\begingroup$ v /. {0 -> False, 1 -> True} should be faster than your approach, if you must start from numerical values. Direct generation of an array of Boolean values with RandomChoice will still be faster though. $\endgroup$
    – MarcoB
    Aug 15, 2023 at 8:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.