how to generate a gaussian distribution using mysql user-defined function

前端 未结 3 1875
南方客
南方客 2020-12-20 22:39

I like to use MySQL to do quantitative analysis and statistics. I would like to make a MySQL user-defined function of the form: sample_gaussian(mean, stdev) that returns a s

3条回答
  •  隐瞒了意图╮
    2020-12-20 23:18

    In answer to my own question, here is a MySQL user-defined function that returns a single random value sampled from a Gaussian distribution with a given mean and standard deviation.

    DROP FUNCTION IF EXISTS gauss;
    DELIMITER //
    CREATE FUNCTION gauss(mean float, stdev float) RETURNS float
    BEGIN
    set @x=rand(), @y=rand();
    set @gaus = ((sqrt(-2*log(@x))*cos(2*pi()*@y))*stdev)+mean;
    return @gaus;
    END
    //
    DELIMITER ;
    

    To verify that this is in fact returning a Gaussian distribution, you can generate a series of these, then plot a histogram:

    create temporary table temp (id int, rando float);
    insert into temp (rando) select gauss(2,1); # repeat this operation 500 times
    insert into temp (rando) select gauss(2,1) from any_table_with_500+_entries limit 500;
    select round(temp,1), count(*) from temp group by round(temp,1) # creates a histogram
    

    If you plot that histogram in excel or graphing tool of choice, you'll see the bell shaped normal curve.

提交回复
热议问题