LDP/LDP/guide/docbook/abs-guide/random2.sh

30 lines
851 B
Bash
Raw Normal View History

2002-01-07 15:25:25 +00:00
#!/bin/bash
2012-11-27 14:56:18 +00:00
# random2.sh: Returns a pseudorandom number in the range 0 - 1,
#+ to 6 decimal places. For example: 0.822725
# Uses the awk rand() function.
2002-01-07 15:25:25 +00:00
AWKSCRIPT=' { srand(); print rand() } '
2012-11-27 14:56:18 +00:00
# Command(s)/parameters passed to awk
2002-01-07 15:25:25 +00:00
# Note that srand() reseeds awk's random number generator.
2003-11-03 16:25:16 +00:00
2002-01-07 15:25:25 +00:00
echo -n "Random number between 0 and 1 = "
2003-11-03 16:25:16 +00:00
2002-01-07 15:25:25 +00:00
echo | awk "$AWKSCRIPT"
2003-11-03 16:25:16 +00:00
# What happens if you leave out the 'echo'?
2002-01-07 15:25:25 +00:00
exit 0
2002-04-01 16:04:17 +00:00
# Exercises:
# ---------
2002-01-07 15:25:25 +00:00
2002-04-01 16:04:17 +00:00
# 1) Using a loop construct, print out 10 different random numbers.
2012-11-27 14:56:18 +00:00
# (Hint: you must reseed the srand() function with a different seed
#+ in each pass through the loop. What happens if you omit this?)
2002-01-07 15:25:25 +00:00
2002-04-01 16:04:17 +00:00
# 2) Using an integer multiplier as a scaling factor, generate random numbers
2012-11-27 14:56:18 +00:00
#+ in the range of 10 to 100.
2002-01-07 15:25:25 +00:00
2002-04-01 16:04:17 +00:00
# 3) Same as exercise #2, above, but generate random integers this time.