Python Generate a random Maxwell distribution from a normal distribution

╄→尐↘猪︶ㄣ 提交于 2020-05-28 04:14:07

问题


I have a set of data that follows a normal distribution in which I can fit the histogram and obtain the mean and 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. Any help would much appreciate it.


回答1:


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



来源:https://stackoverflow.com/questions/61717317/python-generate-a-random-maxwell-distribution-from-a-normal-distribution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!