Modified random distribution: Difference between revisions

m
→‎{{header|UNIX Shell}}: change loop style
m (→‎{{header|UNIX Shell}}: change loop style)
(10 intermediate revisions by 6 users not shown)
Line 215:
0.92..0.96 *******************************************************************
0.96..1.00 ************************************************************************</pre>
 
=={{header|ALGOL 68}}==
{{Trans|Wren|with slightly modified output}}
<syntaxhighlight lang="algol68">
BEGIN # Modified random distribution - translation of the Wren sample #
 
next random; # initialise the random number generator #
 
PROC rng = ( PROC(REAL)REAL modifier )REAL:
BEGIN
REAL r1, r2;
WHILE
r1 := random;
r2 := random;
r2 >= modifier( r1 )
DO SKIP OD;
r1
END # rng # ;
 
PROC modifier = ( REAL x )REAL: 2 * ABS ( 0.5 - x );
 
INT n = 100 000;
INT num bins = 21;
REAL bin size = 1 / num bins;
CHAR hist char = "#";
INT hist char size = 125;
[ 0 : num bins - 1 ]INT bins ; FOR i FROM LWB bins TO UPB bins DO bins[ i ] := 0 OD;
FOR i FROM 0 TO n DO
bins[ ENTIER ( rng( modifier ) / bin size ) ] +:= 1
OD;
 
PROC f2 = ( REAL v )STRING: # formatting routine #
BEGIN
STRING result := fixed( ABS v, 0, 2 );
IF result[ LWB result ] = "." THEN "0" +=: result FI;
IF v < 0 THEN "-" +=: result FI;
result
END # FMT # ;
 
print( ( "Modified random distribution with ", whole( n, 0 ), " samples in range [0, 1):", newline ) );
print( ( " Range Number of samples within that range", newline ) );
FOR i FROM LWB bins TO UPB bins DO
STRING hist = hist char * ROUND ( bins[ i ] / hist char size );
print( ( f2( bin size * i ), " ..< " ) );
print( ( f2( bin size * ( i + 1 ) ), " ", whole( bins[ i ], -5 ), " ", hist, newline ) )
OD
 
END
</syntaxhighlight>
{{out}}
<pre>
Modified random distribution with 100000 samples in range [0, 1):
Range Number of samples within that range
0.00 ..< 0.05 8990 ########################################################################
0.05 ..< 0.10 8043 ################################################################
0.10 ..< 0.14 7265 ##########################################################
0.14 ..< 0.19 6366 ###################################################
0.19 ..< 0.24 5442 ############################################
0.24 ..< 0.29 4631 #####################################
0.29 ..< 0.33 3805 ##############################
0.33 ..< 0.38 2780 ######################
0.38 ..< 0.43 1725 ##############
0.43 ..< 0.48 907 #######
0.48 ..< 0.52 236 ##
0.52 ..< 0.57 915 #######
0.57 ..< 0.62 1778 ##############
0.62 ..< 0.67 2696 ######################
0.67 ..< 0.71 3657 #############################
0.71 ..< 0.76 4539 ####################################
0.76 ..< 0.81 5382 ###########################################
0.81 ..< 0.86 6337 ###################################################
0.86 ..< 0.90 7230 ##########################################################
0.90 ..< 0.95 8173 #################################################################
0.95 ..< 1.00 9104 #########################################################################
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="c++">
#include <cmath>
#include <cstdint>
#include <functional>
#include <iomanip>
#include <iostream>
#include <random>
#include <string>
#include <vector>
 
std::random_device random;
std::mt19937 generator(random());
std::uniform_real_distribution<double> distribution(0.0F, 1.0F);
 
double modifier(const double& x) {
return ( x < 0.5 ) ? 2 * ( 0.5 - x ) : 2 * ( x - 0.5 );
}
 
double modified_random(const std::function<double(double)>& modify) {
double result = -1.0;
 
while ( result < 0.0 ) {
double random_one = distribution(generator);
double random_two = distribution(generator);
if ( random_two < modify(random_one) ) {
result = random_one;
}
}
return result;
}
 
int main() {
const int32_t sample_size = 100'000;
const int32_t bin_count = 20;
const double bin_size = 1.0 / bin_count;
 
std::vector<int32_t> bins(bin_count, 0);
 
for ( int32_t i = 0; i < sample_size; ++i ) {
double random = modified_random(modifier);
int32_t bin_number = floor(random / bin_size);
bins[bin_number]++;
}
 
std::cout << "Modified random distribution with " << sample_size << " samples in range [0, 1):"
<< std::endl << std::endl;
std::cout << " Range Number of samples within range" << std::endl;
 
const int32_t scale_factor = 125;
for ( float i = 0.0; i < bin_count; ++i ) {
std::string histogram = " " + std::string(bins[i] / scale_factor, '#') + " ";
std::cout << std::fixed << std::setw(4)<< std::setprecision(2) << i / bin_count << " ..< "
<< std::setw(4) << ( i + 1.0 ) / bin_count << histogram << bins[i] << std::endl;
}
}
</syntaxhighlight>
{{ out }}
<pre>
Modified random distribution with 100000 samples in range [0, 1):
 
Range Number of samples within range
0.00 ..< 0.05 ############################################################################ 9581
0.05 ..< 0.10 ##################################################################### 8662
0.10 ..< 0.15 ############################################################ 7516
0.15 ..< 0.20 ################################################### 6405
0.20 ..< 0.25 ############################################ 5595
0.25 ..< 0.30 #################################### 4502
0.30 ..< 0.35 ########################### 3464
0.35 ..< 0.40 ################### 2466
0.40 ..< 0.45 ############ 1525
0.45 ..< 0.50 #### 508
0.50 ..< 0.55 ### 482
0.55 ..< 0.60 ########### 1479
0.60 ..< 0.65 ################### 2494
0.65 ..< 0.70 ########################### 3440
0.70 ..< 0.75 ##################################### 4656
0.75 ..< 0.80 ############################################ 5544
0.80 ..< 0.85 ################################################### 6483
0.85 ..< 0.90 ########################################################### 7411
0.90 ..< 0.95 ################################################################### 8389
0.95 ..< 1.00 ########################################################################### 9398
</pre>
 
=={{header|Factor}}==
Line 348 ⟶ 507:
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Modified_random_distribution}}
 
'''Solution'''
 
The following is the modifier random distribution function. It does not contain the modifier function, it is passed as a lambda expression:
 
[[File:Fōrmulæ - Modified random distribution 01.png]]
 
The example modifier is the following:
 
[[File:Fōrmulæ - Modified random distribution 02.png]]
 
The following functions groups a list of numbers in the given number of bins, producing the data necessary for a histogram.
 
[[File:Fōrmulæ - Modified random distribution 03.png]]
 
[[File:Fōrmulæ - Modified random distribution 04.png]]
 
[[File:Fōrmulæ - Modified random distribution 05.png]]
 
'''Test case 1. Showing the histogram of 50,000 numbers in 5 bins'''
 
[[File:Fōrmulæ - Modified random distribution 06.png]]
 
[[File:Fōrmulæ - Modified random distribution 07.png]]
 
'''Test case 2. Showing the histogram of 50,000 numbers in 20 bins'''
 
[[File:Fōrmulæ - Modified random distribution 08.png]]
 
[[File:Fōrmulæ - Modified random distribution 09.png]]
 
'''Test case 3. Showing the histogram of 50,000 numbers in 100 bins'''
 
[[File:Fōrmulæ - Modified random distribution 10.png]]
 
[[File:Fōrmulæ - Modified random distribution 11.png]]
 
=={{header|Go}}==
Line 533 ⟶ 728:
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 
Line 546 ⟶ 742:
final double binSize = 1.0 / binCount;
List<Integer> bins = Stream.generate( () -> 0 ).limit(binCount).collect(Collectors.toList());
for ( int i = 0; i < sampleSize; i++ ) {
Line 611 ⟶ 807:
0.90 ..< 0.95 ################################################################### 8474
0.95 ..< 1.00 ############################################################################ 9557
</pre>
 
=={{header|javascript}}==
 
<syntaxhighlight lang=javascript>function modifier(x) { return (x < .5 ? -1 : +1)*(2*(x-.5)) }
 
function random(m) {
let random1, random2;
while (true) {
random1 = Math.random();
random2 = Math.random();
if (random2 < m(random1)) {
return random1;
}
}
}
 
const N = 10000;
const bins = 20;
var numbers = [];
for (i=0;i<N;i++) {
let number = random(modifier);
numbers.push(number);
}
 
const delta = 1.0/bins;
var count = 0;
for (ceil=delta; ceil<1.0+delta; ceil+=delta) {
for (n of numbers) {
if ((n < ceil) && (ceil - delta <= n)) {
count++;
}
}
let width = count/N * 80;
let bar = '';
 
for (i = 0; i<width; i++) bar+='#';
console.log(bar);
count = 0;
}</syntaxhighlight>
{{out}}
<pre>########
#######
#######
######
#####
####
###
###
##
#
#
##
###
###
####
#####
######
######
#######
########
</pre>
 
Line 1,171 ⟶ 1,428:
0.933333...1.000000 *************************************** 6092
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use ndhistogram::{Histogram, ndhistogram, axis::Uniform};
use rand::Rng;
 
/// change x in [0.0, 1.0) to a split with minimum probability at 0.5
fn modifier(x: f64) -> f64 {
if x < 0.5 {
return 2.0 * (0.5 - &x);
} else {
return 2.0 * (&x - 0.5);
}
}
 
const WANTED: usize = 20_000;
 
fn main() {
let mut hist = ndhistogram!(Uniform::new(19, -0.0, 1.0));
let mut rng = rand::thread_rng();
for _ in 0.. WANTED {
loop {
let x: f64 = rng.gen::<f64>();
let y: f64 = rng.gen::<f64>();
if y < modifier(x) {
hist.fill(&f64::from(x));
break;
}
}
}
println!("{}", hist);
}
</syntaxhighlight>{{out}}
<pre>
VecHistogram1D(21 bins, sum=20000)
(-inf, -0.00) |
[0.00, 0.05) | #################################################
[0.05, 0.11) | ############################################
[0.11, 0.16) | #######################################
[0.16, 0.21) | ##################################
[0.21, 0.26) | ###########################
[0.26, 0.32) | ######################
[0.32, 0.37) | ################
[0.37, 0.42) | ###########
[0.42, 0.47) | #####
[0.47, 0.53) | #
[0.53, 0.58) | #####
[0.58, 0.63) | ###########
[0.63, 0.68) | ###############
[0.68, 0.74) | ######################
[0.74, 0.79) | ############################
[0.79, 0.84) | #################################
[0.84, 0.89) | ######################################
[0.89, 0.95) | ############################################
[0.95, 1.00) | ##################################################
[1.00, inf) |
</pre>
 
=={{header|UNIX Shell}}==
{{works with|bash}}
<syntaxhighlight lang=bash># NOTE: In bash, RANDOM returns an integer from 0 to 32767 (2**15-1)
random() {
local m="$1"
local -i random1 random2
while true
do
random1=RANDOM
random2=RANDOM
if ((random2 < $("$m" $random1)))
then echo $random1; break
fi
done
}
 
modifier() {
local -i x=$1
echo $((x < 2**14 ? 2**14 - x : x - 2**14 ))
}
 
declare -i N=10000 bins=20
declare -a histogram
for ((i=0;i<N;i++))
do ((histogram[bins*$(random modifier)/2**15]++))
done
 
for ((i=0;i<bins;i++))
do
for ((j=0;j< ${histogram[i]-0}*bins*50/N;j++))
do echo -n '#'
done
echo
done</syntaxhighlight>
{{out}}
<pre>#################################################################################################
################################################################################
############################################################################
###################################################################
#######################################################
###############################################
###################################
##########################
#############
######
#####
###############
##########################
##################################
#############################################
#####################################################
##############################################################
#######################################################################
####################################################################################
################################################################################################</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "random" for Random
import "./fmt" for Fmt
 
var rgen = Random.new()
1,934

edits