简体   繁体   English

Python 从正态分布生成随机麦克斯韦分布

[英]Python Generate a random Maxwell distribution from a normal distribution

I have a set of data that follows a normal distribution in which I can fit the histogram and obtain the mean and sigma.我有一组遵循正态分布的数据,我可以在其中拟合直方图并获得均值和 sigma。

For the sake of example, I will approximate it by generating a random normal distribution as follows:为了举例,我将通过生成如下的随机正态分布来近似它:

from scipy.stats import maxwell
import math
import random
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from scipy.optimize import curve_fit
from IPython import embed # put embed() where you want to stop
import matplotlib.ticker as ticker

    data = random.gauss(307, 16)
    N, bins, patches = plt.hist(data, bins=40, density=True, alpha=0.5, histtype='bar', ec='black')
    mu, std = norm.fit(data)
    xmin, xmax = plt.xlim()
    x = np.linspace(xmin, xmax, 100)
    p = norm.pdf(x, mu, std)
    plt.plot(x, p, 'k', linewidth=2, label= r'$\mu$ = '+'{:0.1f}'.format(mu)+r' $\pm$ '+'{:0.1f}'.format(std))

What I would like to do next is to generate a Maxwell distribution from this "normal" distribution and be able to fit我接下来想做的是从这个“正态”分布生成麦克斯韦分布并能够拟合

I have read scipy.stats.maxwell webpage and several other related questions but was not able to generate such a distribution from "a gauss distribution" and fit it.我已阅读scipy.stats.maxwell网页和其他几个相关问题,但无法从“高斯分布”生成这样的分布并拟合它。 Any help would much appreciate it.任何帮助将不胜感激。

Well, knowing that each Maxwell is distribution of the absolute value of the molecule velocity, where each component is normally distributed, you could make sampling like code below好吧,知道每个麦克斯韦是分子速度绝对值的分布,每个分量都是正态分布的,你可以像下面的代码一样进行采样

import numpy as np
import matplotlib.pyplot as plt

from scipy.stats import maxwell

def maxw(size = None):
    """Generates size samples of maxwell"""
    vx = np.random.normal(size=size)
    vy = np.random.normal(size=size)
    vz = np.random.normal(size=size)
    return np.sqrt(vx*vx + vy*vy + vz*vz)

mdata = maxw(100000)
h, bins = np.histogram(mdata, bins = 101, range=(0.0, 10.0))

x = np.linspace(0.0, 10.0, 100)
rv = maxwell()

fig, ax = plt.subplots(1, 1)

ax.hist(mdata, bins = bins, density=True)
ax.plot(x, rv.pdf(x), 'k-', lw=2, label='Maxwell pdf')
plt.title("Maxwell")
plt.show()

And here is the picture with sampling and Maxwell PDF overlapped这是采样和Maxwell PDF重叠的图片

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM