vr has asked for the wisdom of the Perl Monks concerning the following question:

Edit. I hit "Post it" and immediately understand what's the problem with this code. Can this node please be considered for deletion? Sorry :-(

use strict; use warnings; use feature 'say'; my $len = 100_000; my $str = join '', map { int( rand 2 ) ? 0 : 1 } 1 .. $len; say +( $str =~ tr/1/1/ ) / $len; for ( 1 .. 1_000_000 ) { my $pos = int rand $len; my $chr = substr $str, $pos, 1; substr( $str, $pos, 1, int( rand 2 ) ? 0 : 1 ) if $chr } say +( $str =~ tr/1/1/ ) / $len;
$ perl 171126.pl 0.4988 0.00312

Removing the if $chr (or replacing it with e.g. if time) gives expected output (i.e. "1"s percentage stays around .5). It's SSCCE from larger experiment, never mind what this useless fragment is about.

$ perl -v This is perl 5, version 26, subversion 0 (v5.26.0) built for x86_64-li +nux-thread-multi (with 1 registered patch, see perl -V for more detail)

Replies are listed 'Best First'.
Re: Looks like something is broken
by LanX (Saint) on Nov 26, 2017 at 17:39 UTC
    Your condition if $chr means only "1" characters are replaced by either 0 or 1, because $chr=0 is false.

    So obviously the proportion of "0" characters is growing with each replacement in your loop.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Wikisyntax for the Monastery