Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Tilted uniform distribution random number generator over min/max range
#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; }
run
|
edit
|
history
|
help
0
general
unordered graphs search
Print system time
for_each_argument
CS1428 SI Tuesday
Access namespace by unqualified manner
marquee text in C++
appliWall
STL stack
DESim Example Starter Code