vult-dsp / vult

Vult is a transcompiler well suited to write high-performance DSP code
https://vult-dsp.github.io/vult
Other
496 stars 25 forks source link

No random generator in the language reference #16

Closed cristiano-belloni closed 7 years ago

cristiano-belloni commented 7 years ago

Hello, I was looking at the reference wiki and found no random() function in the "mathematical functions" section.

I guess one could always implement its own PRNG but I was wondering if it is something you would consider to add or it's missing by design?

modlfo commented 7 years ago

As a workaround, you can find a random function generator in this file https://github.com/modlfo/vult-examples/blob/master/src/osc_noisef.vult (the function osc_noisef). I use it to generate audio noise. But I can add a similar function as part of the builtin functions.

cristiano-belloni commented 7 years ago

I will, thank you.

Still, it would be cool to demand randomization to the target language (similarly on how you use the Math methods with Javascript), where possible, and fallback to the noise osc where not - mainly because of performance (if you use the system random generator, chances are that it's faster than generating samples one by one) and random seeding (instead, with the noise osc, x1 always starts at 0, and the sequence is always the same).

It's probably something that doesn't make any difference in 99% of the cases, though.

modlfo commented 7 years ago

I have implemented two new functions: random() and irandom() for real and int types. The implementation is based on the random functions available in the target language. I did not implement the seed function to define the initial seed because seems like JavaScript does not provide it.

I believe (but I haven't tested it yet) that a random function generator as the following code can be faster:

fun noise() {
   mem x1 = (x1 * 17389 + 7919) % 32768;
   val y1 = real(x1)/32768.0;
   return y1;
}

The reason I believe that is because the operations involved are very simple but randomness is not very good. The algorithms behind rand() in C or Math.random() in Js may be more sophisticated.

cristiano-belloni commented 7 years ago

Wow, that was fast, thank you! Regarding speed, I still believe that the Javascript Math.random native version is faster - I think it's implemented natively, instead of being interpreted. As for being a "good" generator, the PRNG you posted is deterministic and modulus based (so when a number is repeated, the cycle restarts) and has a full cycle period of 32769 pseudo random numbers - yep, not the longest generator in the world, as you suspected :) Thanks!