Page 82 - JavaScript
P. 82
function oscillator(time, frequency = 1, amplitude = 1, phase = 0, offset = 0){
var t = time * frequency * Math.PI * 2; // get phase at time
t += phase * Math.PI * 2; // add the phase offset
var v = Math.sin(t); // get the value at the calculated position in the cycle
v *= amplitude; // set the amplitude
v += offset; // add the offset
return v;
}
Or in a more compact (and slightly quicker form):
function oscillator(time, frequency = 1, amplitude = 1, phase = 0, offset = 0){
return Math.sin(time * frequency * Math.PI * 2 + phase * Math.PI * 2) * amplitude +
offset;
}
All the arguments apart from time are optional
Simulating events with different probabilities
Sometimes you may only need to simulate an event with two outcomes, maybe with different
probabilities, but you may find yourself in a situation that calls for many possible outcomes with
different probabilities. Let's imagine you want to simulate an event that has six equally probable
outcomes. This is quite simple.
function simulateEvent(numEvents) {
var event = Math.floor(numEvents*Math.random());
return event;
}
// simulate fair die
console.log("Rolled a "+(simulateEvent(6)+1)); // Rolled a 2
However, you may not want equally probable outcomes. Say you had a list of three outcomes
represented as an array of probabilities in percents or multiples of likelihood. Such an example
might be a weighted die. You could rewrite the previous function to simulate such an event.
function simulateEvent(chances) {
var sum = 0;
chances.forEach(function(chance) {
sum+=chance;
});
var rand = Math.random();
var chance = 0;
for(var i=0; i<chances.length; i++) {
chance+=chances[i]/sum;
if(rand<chance) {
return i;
}
}
// should never be reached unless sum of probabilities is less than 1
// due to all being zero or some being negative probabilities
return -1;
https://riptutorial.com/ 39

