Last active
November 9, 2015 17:28
-
-
Save KushalP/2c6dc8f413ede7f46df1 to your computer and use it in GitHub Desktop.
Annotated some of the source of code that exists here: http://www.firstpr.com.au/dsp/pink-noise/#Voss I've annotated using multiline code blocks that are surrounded with /** and */
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdlib.h> | |
class PinkNumber { | |
private: | |
int max_key; | |
int key; | |
unsigned int range; | |
unsigned int white_values[5]; | |
public: | |
PinkNumber(unsigned int range = 128) { | |
max_key = 0x1f; // Five bits set | |
this->range = range; | |
key = 0; | |
/** | |
* This is the end of the constructor for this PinkNumber object. | |
* | |
* It fills an array that has five elements (see line 9 of this file) | |
* with some values. The values are generated up to a maximum of the | |
* range provided. By default, the range is 128, which means the | |
* white noise values are set between 0 and (128 / 5). | |
*/ | |
for (int i = 0; i < 5; i++) { | |
white_values[i] = rand() % (range/5); | |
} | |
} | |
int GetNextValue() { | |
int last_key = key; | |
unsigned int sum; | |
key++; | |
if (key > max_key) { | |
key = 0; | |
} | |
// Exclusive-Or previous value with current value. This gives | |
// a list of bits that have changed. | |
/** | |
* XOR is a bit of a difficult thing to get your head around, but the | |
* best thing to read is this: | |
* - https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/xor.html | |
* - https://en.wikipedia.org/wiki/Exclusive_or | |
*/ | |
int diff = last_key ^ key; | |
sum = 0; | |
for (int i = 0; i < 5; i++) { | |
// If bit changed get new random number for corresponding | |
// white_value | |
if (diff & (1 << i)) { | |
white_values[i] = rand() % (range/5); | |
} | |
sum += white_values[i]; | |
} | |
return sum; | |
} | |
}; | |
int main() { | |
PinkNumber pn; | |
for (int i = 0; i < 100; i++) { | |
std::cout << pn.GetNextValue() << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment