Add info to documentation about random numbers, initialize srand (#2056)

Issue #2053 has highlighted the fact that random numbers are always generated with the same seed.
An example of generating different random numbers, other than the original seed, has been added to the documentation.
Furthermore srand initialization has been added to jerry-main, and targets.
Update test-common.h with srand call.

JerryScript-DCO-1.0-Signed-off-by: Daniel Balla dballa@inf.u-szeged.hu
This commit is contained in:
Daniel Balla
2017-11-03 15:31:57 +01:00
committed by László Langó
parent 678fcb20ed
commit 4690d128b3
9 changed files with 52 additions and 19 deletions
+44
View File
@@ -551,6 +551,50 @@ Value of x is 12
Value of x is 17
```
## Step 8. Changing the seed of pseudorandom generated numbers
If you want to change the seed of `Math.random()` generated numbers, you have to initialize the seed value with `srand`.
A recommended method is using `jerry_port_get_current_time()` or something based on a constantly changing value, therefore every run produces truly random numbers.
[doctest]: # ()
```c
#include <string.h>
#include <stdlib.h>
#include "jerryscript.h"
#include "jerryscript-port.h"
#include "jerryscript-ext/handler.h"
int
main (void)
{
/* Initialize srand value */
srand ((unsigned) jerry_port_get_current_time ());
/* Generate a random number, and print it */
const jerry_char_t script[] = "var a = Math.random (); print(a)";
size_t script_size = strlen ((const char *) script);
/* Initialize the engine */
jerry_init (JERRY_INIT_EMPTY);
/* Register the print function */
jerryx_handler_register_global ((const jerry_char_t *) "print",
jerryx_handler_print);
/* Evaluate the script */
jerry_value_t eval_ret = jerry_eval (script, script_size, false);
/* Free the JavaScript value returned by eval */
jerry_release_value (eval_ret);
/* Cleanup the engine */
jerry_cleanup ();
return 0;
}
```
## Further steps
For further API description, please visit [API Reference page](https://jerryscript-project.github.io/jerryscript/api-reference/) on [JerryScript home page](https://jerryscript-project.github.io/jerryscript/).