Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Tilted uniform distribution random number generator over min/max range
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
#include <iostream> #include <iomanip> #include <string> #include <map> #include <cmath> // -------- CONFIG -------- float min = -10; float max = 10; float tilt = 1.; // ------------------------ using std::cout; using std::endl; static bool debug = false; float randomRange(float min, float max, float tilt = 0); int main() { srand(time(NULL)); if (debug) { cout << randomRange(min, max, tilt) << endl; return 0; } std::map<int, int> hist; for (int i = 0; i < 1000000; ++i) { ++hist[round(randomRange(min, max, tilt))]; } for (auto p : hist) { std::cout << std::fixed << std::setprecision(1) << std::setw(3) << p.first << ' ' << p.second << '\t' << std::string(p.second/2000, '*') << '\n'; } } float randomRange(float min, float max, float tilt) { float rnd = min + static_cast<float>(rand()) / static_cast<float>(RAND_MAX / (max - min)); if (debug) cout << "rnd: " << rnd << endl; if (0 == tilt) return rnd; float middle = (min + max)/2.F; if (debug) cout << "middle: " << middle << endl; // Calculate probability float deviation = (((rnd - min)/(max - min)) - 0.5F) / 0.5F; if (debug) cout << "deviation: " << deviation << endl; float probability = -deviation * tilt; if (debug) cout << "probability: " << probability << endl; if (probability < 0) { if (debug) cout << "Negative probability. Return original random." << endl << endl; return rnd; } float dice = static_cast<float>(rand()) / static_cast<float>(RAND_MAX); if (debug) cout << dice << " "; if (dice > probability) { if (debug) cout << "--> no flip. Return original random." << endl << endl; return rnd; } float counterpart = min + max - rnd; if (debug) cout << "--> FLIP! Return counterpart." << endl << endl; return counterpart; }
clang++
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 0.62 sec, absolute running time: 0.14 sec, cpu time: 0.06 sec, memory peak: 3 Mb, absolute service time: 0,76 sec
edit mode
|
history
|
discussion