Hướng dẫn dùng np rand trong PHP

Đôi lúc chúng ta lập trình cần đến những con số sinh ngẫu nhiên vào những công việc khách nhau hôm này mình xin giới thiệu với mọi người hàm sinh số ngẫu nhiên trong PHP

Show
Mục lục

    Hàm rand()

    Hàm này sinh ra một số int ngẫu nhiên

    Hàm rand(int1, int2)

    Hàm này sinh ra một số ngẫu nhiên trong khoảng từ số int1 đến int2

    Ví dụ:

    ";
        echo rand(3,9);    //tạo số ngẫu nhiên trong khoảng từ 3->9
    ?>

    Hàm ngẫu nhiển trong mảng PHP - array_rand($array, int)

    Hàm sẽ lấy ra số phần tử ngẫu nhiên trong mang, có 2 tham số $array là mảng cần lấy phần tử ngẫu nhiên và int là số phần tử cần lấy

    hàm trả về index key ngẫu nhiên

    ví dụ:




    Ngẫu nhiên là một mô-đun có trong thư viện NumPy. Mô-đun này chứa các hàm được sử dụng để tạo số ngẫu nhiên. Mô-đun này chứa một số phương pháp tạo dữ liệu ngẫu nhiên đơn giản, một số hàm hoán vị và phân phối cũng như các hàm tạo ngẫu nhiên.

    Các bài viết liên quan:

    Tất cả các chức năng trong một mô-đun ngẫu nhiên như sau:

    Random data

    Dữ liệu ngẫu nhiên đơn giản có các chức năng sau:

    1. p.random.rand (d0, d1, …, dn)

    Chức năng này của mô-đun ngẫu nhiên được sử dụng để tạo ra các số hoặc giá trị ngẫu nhiên trong một hình dạng nhất định.

    Thí dụ:

    import numpy as np  
    a=np.random.rand(5,2)  
    a  

    Output:

    1. np.random.randn (d0, d1, …, dn)

    Hàm này của mô-đun ngẫu nhiên trả về một mẫu từ phân phối “chuẩn thông thường”.

    Thí dụ:

    import numpy as np  
    a=np.random.randn(2,2)  
    a

    Output:

    1. np.random.randint (low [, high, size, dtype])

    Chức năng này của mô-đun ngẫu nhiên được sử dụng để tạo ra các số nguyên ngẫu nhiên từ bao gồm (thấp) đến loại trừ (cao).

    Thí dụ:

    import numpy as np  
    a=np.random.randint(3, size=10)  
    a

    Output:

    1. np.random.random_integers (low[, high, size])

    Hàm này của mô-đun ngẫu nhiên được sử dụng để tạo số nguyên ngẫu nhiên kiểu np.int giữa thấp và cao.

    Thí dụ:

    import numpy as np  
    a=np.random.random_integers(3)  
    a  
    b=type(np.random.random_integers(3))  
    b  
    c=np.random.random_integers(5, size=(3,2))  
    c  

    Output:

    1. np.random.random_sample ([size])

    Chức năng này của mô-đun ngẫu nhiên được sử dụng để tạo số lượng phao ngẫu nhiên trong khoảng thời gian nửa mở [0.0, 1.0).

    Thí dụ:

    import numpy as np  
    a=np.random.random_sample()  
    a  
    b=type(np.random.random_sample())  
    b  
    c=np.random.random_sample((5,))  
    c  

    Output:

    1. np.random.random ([size])

    Chức năng này của mô-đun ngẫu nhiên được sử dụng để tạo số lượng phao ngẫu nhiên trong khoảng thời gian nửa mở [0.0, 1.0).

    Thí dụ:

    import numpy as np  
    a=np.random.random()  
    a  
    b=type(np.random.random())  
    b  
    c=np.random.random((5,))  
    c  
    

    Output:

    1. np.random.ranf ([size])

    Chức năng này của mô-đun ngẫu nhiên được sử dụng để tạo số lượng phao ngẫu nhiên trong khoảng thời gian nửa mở [0.0, 1.0).

    Thí dụ:

    import numpy as np  
    a=np.random.ranf()  
    a  
    b=type(np.random.ranf())  
    b  
    c=np.random.ranf((5,))  
    c  

    Output:

    1. np.random.sample ([size])

    Chức năng này của mô-đun ngẫu nhiên được sử dụng để tạo số lượng phao ngẫu nhiên trong khoảng thời gian nửa mở [0.0, 1.0).

    Các bài viết khác:

    Thí dụ:

    import numpy as np  
    a=np.random.sample()  
    a  
    b=type(np.random.sample())  
    b  
    c=np.random.sample((5,))  
    c  
    

    Output:

    1. np.random.choice (a [, size, Replace, p])

    Chức năng này của mô-đun ngẫu nhiên được sử dụng để tạo mẫu ngẫu nhiên từ một mảng 1-D nhất định.

    Thí dụ:

    import numpy as np  
    a=np.random.choice(5,3)  
    a  
    b=np.random.choice(5,3, p=[0.2, 0.1, 0.4, 0.2, 0.1])  
    b  
    

    Output:

    1. np.random.bytes (length)

    Chức năng này của mô-đun ngẫu nhiên được sử dụng để tạo ra các byte ngẫu nhiên.

    Thí dụ:

    import numpy as np  
    a=np.random.bytes(7)  
    a  

    Output:

    Hoán vị

    Có các chức năng sau của hoán vị:

    1. np.random.shuffle ()

    Hàm này được sử dụng để sửa đổi một trình tự tại chỗ bằng cách xáo trộn nội dung của nó.

    Thí dụ:

    import numpy as np  
    a=np.arange(12)  
    a  
    np.random.shuffle(a)  
    a  

    Output:

    1. np.random.permutation ()

    Hàm này hoán vị một dãy ngẫu nhiên hoặc trả về một dãy đã hoán vị.

    Thí dụ:

    import numpy as np  
    a=np.random.permutation(12)  
    a  

    Output:

    Phân phối

    Có các chức năng sau của hoán vị:

    1. beta (a, b [, size])

    Hàm này được sử dụng để vẽ mẫu từ bản phân phối Beta.

    Thí dụ:

    def setup(self):  
            self.dist = dist.beta  
            self.cargs = []  
            self.ckwd = dict(alpha=2, beta=3)  
            self.np_rand_fxn = numpy.random.beta  
            self.np_args = [2, 3]  
            self.np_kwds = dict() 
    1. binomial (n, p [, size])

    Hàm này được sử dụng để lấy mẫu từ một phân phối nhị thức.

    Thí dụ:

    import numpy as np  
    n, p = 10, .6  
    s1= np.random.binomial(n, p, 10)  
    s1  

    Output:

    1. chisquare (df [, size])

    Hàm này được sử dụng để lấy mẫu từ một phân phối nhị thức.

    Thí dụ:

    import numpy as np  
    np.random.chisquare(2,4)  
    sum(np.random.binomial(9, 0.1, 20000) == 0)/20000.  

    Output:

    1. dirichlet (alpha [, size])

    Hàm này được sử dụng để vẽ một mẫu từ phân phối Dirichlet.

    Thí dụ:

    Import numpy as np  
    import matplotlib.pyplot as plt  
    s1 = np.random.dirichlet((10, 5, 3), 20).transpose()  
    plt.barh(range(20), s1[0])  
    plt.barh(range(20), s1[1], left=s1[0], color='g')  
    plt.barh(range(20), s1[2], left=s1[0]+s1[1], color='r')  
    plt.title("Lengths of Strings")  
    plt.show()  

    Output:

    1. exponential([scale, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối hàm mũ.

    Thí dụ:

    def __init__(self, sourceid, targetid):  
            self.__type = 'Transaction'  
            self.id = uuid4()  
            self.source = sourceid  
            self.target = targetid  
            self.date = self._datetime.date(start=2015, end=2019)  
            self.time = self._datetime.time()  
      
            if random() < 0.05:  
                self.amount = self._numbers.between(100000, 1000000)  
            self.amount = npr.exponential(10)  
      
            if random() < 0.15:  
                self.currency = self._business.currency_iso_code()  
            else:  
                self.currency = None  
    
    1. f (dfnum, dfden [, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối F.

    Thí dụ:

    import numpy as np  
    dfno= 1.  
    dfden = 48.  
    s1 = np.random.f(dfno, dfden, 10)  
    np.sort(s1)  

    Output:

    1.  gamma(shape[, scale, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối Gamma

    Thí dụ:

    import numpy as np  
    shape, scale = 2., 2.  
    s1 = np.random.gamma(shape, scale, 1000)  
    import matplotlib.pyplot as plt  
    import scipy.special as spss  
    count, bins, ignored = plt.hist(s1, 50, density=True)  
    a = bins**(shape-1)*(np.exp(-bins/scale) /  
    (spss.gamma(shape)*scale**shape))  
    plt.plot(bins, a, linewidth=2, color='r')  
    plt.show()  
    1. geometric(p[, size])

    Hàm này được sử dụng để lấy mẫu từ một phân bố hình học.

    Thí dụ:

    import numpy as np  
    a = np.random.geometric(p=0.35, size=10000)  
    (a == 1).sum() / 1000  

    Output:

    1. gumbel ([loc, scale, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối Gumble.

    Thí dụ:

    import numpy as np  
    lov, scale = 0, 0.2  
    s1 = np.random.gumbel(loc, scale, 1000)  
    import matplotlib.pyplot as plt  
    count, bins, ignored = plt.hist(s1, 30, density=True)  
    plt.plot(bins, (1/beta)*np.exp(-(bins - loc)/beta)* np.exp( -np.exp( -(bins - loc) /beta) ),linewidth=2, color='r')  
    plt.show()  
    

    Output:

    1. hypergeometric (ngood, nbad, nsample [, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối Hypergeometric.

    Thí dụ:

    import numpy as np  
    good, bad, samp = 100, 2, 10  
    s1 = np.random.hypergeometric(good, bad, samp, 1000)  
    plt.hist(s1)  
    plt.show()  

    Output:

    1. laplace ([loc, scale, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối Laplace hoặc phân phối hàm mũ kép với vị trí và tỷ lệ xác định.

    Thí dụ:

    import numpy as np  
    location, scale = 0., 2.  
    s = np.random.laplace(location, scale, 10)  
    s  

    Output:

    1. logistic([loc, scale, size])

    Chức năng này được sử dụng để lấy mẫu từ phân phối logistic.

    Thí dụ:

    import numpy as np  
    import matplotlib.pyplot as plt  
    location, scale = 10, 1  
    s1 = np.random.logistic(location, scale, 10000)  
    count, bins, ignored = plt.hist(s1, bins=50)  
    count  
    bins  
    ignored  
    plt.show()  

    Output:

    1.  lognormal([mean, sigma, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối log-chuẩn.

    Thí dụ:

    import numpy as np  
    mu, sigma = 2., 1.  
    s1 = np.random.lognormal(mu, sigma, 1000)  
    import matplotlib.pyplot as plt  
    count, bins, ignored = plt.hist(s1, 100, density=True, align='mid')  
    a = np.linspace(min(bins), max(bins), 10000)  
    pdf = (np.exp(-(np.log(a) - mu)**2 / (2 * sigma**2))/ (a * sigma * np.sqrt(2 * np.pi)))  
    plt.plot(a, pdf, linewidth=2, color='r')  
    plt.axis('tight')  
    plt.show()  

    Output:

    14) logseries (p [, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối logarit.

    Thí dụ:

    import numpy as np  
    x = .6  
    s1 = np.random.logseries(x, 10000)  
    count, bins, ignored = plt.hist(s1)  
    def logseries(k, p):  
    return -p**k/(k*log(1-p))  
    plt.plot(bins, logseries(bins, x)*count.max()/logseries(bins, a).max(), 'r')  
    plt.show() 

    Output:

    1. multinomial(n, pvals[, size])

    Hàm này được sử dụng để lấy mẫu từ một phân phối đa thức.

    Thí dụ:

    import numpy as np  
    np.random.multinomial(20, [1/6.]*6, size=1)  

    Output:

    1. multivariate_normal(mean, cov[, size, …)

    Hàm này được sử dụng để lấy mẫu từ phân phối chuẩn đa biến.

    Thí dụ:

    import numpy as np  
    mean = (1, 2)  
    coveriance = [[1, 0], [0, 100]]   
    import matplotlib.pyplot as plt  
    a, b = np.random.multivariate_normal(mean, coveriance, 5000).T  
    plt.plot(a, b, 'x')  
    plt.axis('equal'023  
    030  
    )  
    plt.show()  

    Output:

    1. negative_binomial (n, p [, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối nhị thức âm.

    Thí dụ:

    import numpy as np  
    s1 = np.random.negative_binomial(1, 0.1, 100000)  
    for i in range(1, 11):  
    probability = sum(s1
    
    
    

    1. rayleigh([scale, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối Rayleigh.

    Thí dụ:

    val = hist(np.random.rayleigh(3, 100000), bins=200, density=True)  
    meanval = 1  
    modeval = np.sqrt(2 / np.pi) * meanval  
    s1 = np.random.rayleigh(modeval, 1000000)  
    100.*sum(s1>3)/1000000.  

    Output:

    1. standard_cauchy ([size])

    Hàm này được sử dụng để lấy mẫu từ phân phối Cauchy tiêu chuẩn với mode = 0.

    Thí dụ:

    import numpy as np  
    import matplotlib.pyplot as plt  
    s1 = np.random.standard_cauchy(1000000)  
    s1 = s1[(s1>-25) & (s1<25)]  # truncate distribution so it plots well  
    plt.hist(s1, bins=100)  
    plt.show()  

    Output:

    1. standard_exponential ([size])

    Hàm này được sử dụng để lấy mẫu từ phân phối mũ tiêu chuẩn.

    Thí dụ:

    import numpy as np  
    n = np.random.standard_exponential((2, 7000))  

    Output:

    1. standard_gamma ([size])

    Hàm này được sử dụng để lấy mẫu từ phân phối Gamma chuẩn.

    Thí dụ:

    import numpy as np  
    shape, scale = 2., 1.  
    s1 = np.random.standard_gamma(shape, 1000000)  
    import matplotlib.pyplot as plt  
    import scipy.special as sps  
    count1, bins1, ignored1 = plt.hist(s, 50, density=True)  
    y = bins1**(shape-1) * ((np.exp(-bins1/scale))/ (sps.gamma(shape) * scale**shape))  
    plt.plot(bins1, y, linewidth=2, color='r')  
    plt.show()  

    Output:

    1. standard_normal ([size])

    Hàm này được sử dụng để lấy mẫu từ một phân phối Chuẩn chuẩn.

    Thí dụ:

    import numpy as np  
    import matplotlib.pyplot as plt  
    s1= np.random.standard_normal(8000)  
    s1  
    q = np.random.standard_normal(size=(3, 4, 2))  
    q   

    Đầu ra:

    1. standard_t (df [, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối Student chuẩn với bậc tự do df.

    Thí dụ:

    intake = np.array([5260., 5470, 5640, 6180, 6390, 6515, 6805, 7515,8230,8770])  
    s1 = np.random.standard_t(10, size=100000)  
    np.mean(intake)  
    intake.std(ddof=1)  
    t = (np.mean(intake)-7725)/(intake.std(ddof=1)/np.sqrt(len(intake)))  
    h = plt.hist(s1, bins=100, density=True)  
    np.sum(s1

    Output:

    1. triangular(left, mode, right[, size])

    Hàm này được sử dụng để lấy mẫu từ một phân bố tam giác trong khoảng thời gian.

    Thí dụ:

    import numpy as np  
    import matplotlib.pyplot as plt  
    h = plt.hist(np.random.triangular(-4, 0, 8, 1000000), bins=300,density=True)  
    plt.show()  

    Output:

    1. uniform([low, high, size])

    Chức năng này được sử dụng để lấy mẫu từ một phân phối đồng đều.

    Thí dụ:

    import numpy as np  
    import matplotlib.pyplot as plt  
    s1 = np.random.uniform(-1,0,1000)  
    np.all(s1 >= -1)  
    np.all(s1 < 0)  
    count, bins, ignored = plt.hist(s1, 15, density=True)  
    plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')  
    plt.show()  

    Output:

    1. vonmises (m1, m2 [, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối von Mises.

    Thí dụ:

    import numpy as np  
    import matplotlib.pyplot as plt  
    m1, m2 = 0.0, 4.0  
    s1 = np.random.vonmises(m1, m2, 1000)  
    from scipy.special import i0  
    plt.hist(s1, 50, density=True)  
    x = np.linspace(-np.pi, np.pi, num=51)  
    y = np.exp(m2*np.cos(x-m1))/(2*np.pi*i0(m2))  
    plt.plot(x, y, linewidth=2, color='r')  
    plt.show()  

    Output:

    1. wald(mean, scale[, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối Wald, hoặc nghịch đảo Gaussian.

    Thí dụ:

    import numpy as np  
    import matplotlib.pyplot as plt  
    h = plt.hist(np.random.wald(3, 3, 100000), bins=250, density=True)  
    plt.show()  

    Output:

    1. weibull (a [, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối Weibull.

    Thí dụ:

    import numpy as np  
    import matplotlib.pyplot as plt  
    from scipy import special  
    x=2.0  
    s=np.random.weibull(x, 1000)  
    a = np.arange(1, 100.)/50.  
    def weib(x, n, a):  
    return (a/n)*(x/n)**np.exp(-(x/n)**a)  
    count, bins, ignored = plt.hist(np.random.weibull(5.,1000))  
    a= np.arange(1,100.)/50.  
    scale = count.max()/weib(x, 1., 5.).max()  
    scale = count.max()/weib(a, 1., 5.).max()  
    plt.plot(x, weib(x, 1., 5.)*scale)  
    plt.show()  

    Output:

    1. zipf (a [, size])

    Hàm này được sử dụng để lấy mẫu từ phân phối Zipf.

    Thí dụ:

    import numpy as np  
    import matplotlib.pyplot as plt  
    from scipy import special  
    x=2.0  
    s=np.random.zipf(x, 1000)  
    count, bins, ignored = plt.hist(s[s<50], 50, density=True)  
    a = np.arange(1., 50.)  
    b= a**(-x) / special.zetac(x)  
    plt.plot(a, b/max(b), linewidth=2, color='r')  
    plt.show() 

    Output: