Skip to content

Commit 5468359

Browse files
committed
Added randomGaussian function
1 parent 04b60a0 commit 5468359

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='STRICT_TRANS_TABLES';
2+
3+
DROP FUNCTION IF EXISTS randomGaussian;
4+
5+
DELIMITER //
6+
7+
CREATE FUNCTION randomGaussian (mu DOUBLE, sigma DOUBLE)
8+
RETURNS DOUBLE
9+
NOT DETERMINISTIC
10+
NO SQL
11+
SQL SECURITY DEFINER
12+
COMMENT 'Returns a random number based on a normal (gaussian) distribution. (v1.00)'
13+
14+
/*****************************************************************************
15+
*
16+
* DESCRIPTION: Returns a random number based on a normal (gaussian) distribution.
17+
*
18+
* AUTHOR: Benoît St-Jean <bstjean@yahoo.com>
19+
* URL: http://www.endormitoire.wordpress.com
20+
* VERSION: 1.00
21+
*
22+
* USAGE: SELECT randomGaussian(12.5, 3.2216);
23+
* RESULT: 10.284951047046617 (this function is NOT deterministic!)
24+
*
25+
* PARAMETERS: mu mean of the gaussian distribution
26+
* sigma standard deviation of the gaussian distribution
27+
*
28+
* RETURN: DOUBLE
29+
*
30+
* NOTES: n/a
31+
*
32+
******************************************************************************/
33+
BEGIN
34+
DECLARE x DOUBLE;
35+
DECLARE v1 DOUBLE;
36+
DECLARE v2 DOUBLE;
37+
38+
IF (mu IS NULL) THEN
39+
SIGNAL SQLSTATE '45000'
40+
SET MESSAGE_TEXT = 'Mean must not be NULL';
41+
ELSEIF (sigma IS NULL) THEN
42+
SIGNAL SQLSTATE '45000'
43+
SET MESSAGE_TEXT = 'Standard deviation must not be NULL';
44+
END IF;
45+
46+
SET v1 := RAND();
47+
SET v2 := RAND();
48+
49+
SET x := SQRT(-2.0 * LOG(v1)) * COS(2.0 * PI() * v2);
50+
RETURN (mu + (sigma * x));
51+
52+
END//
53+
54+
DELIMITER ;
55+
56+
SET SQL_MODE=@OLD_SQL_MODE;

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ A collection of useful (I hope!) functions, stored procedures and SQL scripts to
1212
**isState** : Returns 1 if argument is an American 2-letter state code, 0 otherwise.
1313
**isStrictlyAlpha** : Returns 1 if the string only contains [A-Za-z] characters, 0 otherwise
1414
**lastindexof** : Returns the position of the last occurrence of a substring in a source string.
15-
**occurrences** : Returns the number of occurrences of a search string inside a source string.
15+
**occurrences** : Returns the number of occurrences of a search string inside a source string.
16+
**randomGaussian** : Returns a random number based on a normal (gaussian) distribution.
1617
**randomInt** : Returns a random positive integer between 2 unsigned integers *inclusively*
1718
**removeAllChars** : Removes all characters in a string from a source string.
1819
**replaceAllChars** : Replaces all characters in a string by a single replacement character from source string.

0 commit comments

Comments
 (0)