Hello everyone. First post here.
I tried searching for how to do normal distribution in Sugarcube 2 but nothing comes up, but I could find how to do it in javascript (which I know next to nothing about). I did find this javascript function that fits the bill for what I want and I want to know how I can implement it in the 'Edit Story Javascript' menu for use with Sugarcube 2:
// returns a gaussian random function with the given mean and stdev.
function gaussian(mean, stdev) {
var y2;
var use_last = false;
return function() {
var y1;
if(use_last) {
y1 = y2;
use_last = false;
}
else {
var x1, x2, w;
do {
x1 = 2.0 * Math.random() - 1.0;
x2 = 2.0 * Math.random() - 1.0;
w = x1 * x1 + x2 * x2;
} while( w >= 1.0);
w = Math.sqrt((-2.0 * Math.log(w))/w);
y1 = x1 * w;
y2 = x2 * w;
use_last = true;
}
var retval = mean + stdev * y1;
if(retval > 0)
return retval;
return -retval;
}
}
I found this at
http://stackoverflow.com/questions/25582882/javascript-math-random-normal-distribution-gaussian-bell-curve.
At first I tried other methods that worked, but they didn't have mean and standard deviation variables which I need, but I have no idea how to convert this from javascript. So how can I get this to work in Sugarcube 2 so I can just write <<set $variable to gaussian(80, 10)>> for example?
Thanks in advance.
Comments
That bit of code is what's known as a factory—i.e. it returns an object or function for you to use, it doesn't return data directly. In this case, it's a factory for Gaussian functions.
Open your project's Story JavaScript, paste that code into it, and then do something like the following after it: That creates a Gaussian function, which when called will give the results you're looking for, and assigns it to the special setup object with the name standard.
To use it within your code:
You may name the created function, or functions if you need more than one distribution, pretty much whatever you want.
Edit: Realised that though it now works, I couldn't actually change the value of the mean and standard deviation of the gaussian function within a passage.
How do I make it so that I can for example type:
As I noted before, however, you may generate as many Gaussian functions as you need, just give them unique names. For example: And to use them within your code: Those names are pretty bad, however, you should get the idea.