[英]How to weigh a function with 2 variables with a Gaussian distribution in python?
在過去的幾天里,我一直在使用此工具,但我仍然看不出問題出在哪里。
我正在嘗試在具有特定平均值( R0
)和偏差( sigma
)的高斯分布g(r)
內對具有2個變量f(q,r)
的函數加權。 這是必要的,因為理論函數f(q)
在進行實驗分析時在其r
變量中具有一定的分散性。 因此,我們使用概率密度函數來權衡r
變量中的r
。
我包含了可以正常工作的代碼,但沒有給出預期的結果(隨着多分散度的增加,加權曲線應該更平滑(較高的sigma
),如下所示。如您所見,我整合了兩個函數的卷積從r = 0
到r = +inf
f(r,q)*g(r)
。
繪制結果以將稱量結果與簡單功能進行比較:
from scipy.integrate import quad, quadrature
import numpy as np
import math as m
import matplotlib.pyplot as plt
#function weighted with a probability density function (gaussian)
def integrand(r,q):
#gaussian function normalized
def gauss_nor(r):
#gaussian function
def gauss(r):
return m.exp(-((r-R0)**2)/(2*sigma**2))
return (m.exp(-((r-R0)**2)/(2*sigma**2)))/(quad(gauss,0,np.inf)[0])
#function f(r,q)
def f(r,q):
return 3*(np.sin(q*r)-q*r*np.cos(q*r))/((r*q)**3)
return gauss_nor(r)*f(r,q)
#quadratic integration of the integrand (from 0 to +inf)
#integrand is function*density_function (gauss)
def function(q):
return quad(integrand, 0, np.inf, args=(q))[0]
#parameters used in the function
R0=20
sigma=5
#range to plot q
q=np.arange(0.001,2.0,0.005)
#vector where the result of the integral will be saved
function_vec = np.vectorize(function)
#vector for the squared power of the integral
I=[]
I=(function_vec(q))**2
#function without density function
I0=[]
I0=(3*(np.sin(q*R0)-q*R0*np.cos(q*R0))/((R0*q)**3))**2
#plot of weighted and non-weighted functions
p1,=plt.plot(q,I,'b')
p3,=plt.plot(q,I0,'r')
plt.legend([p1,p3],('Weighted','No weighted'))
plt.yscale('log')
plt.xscale('log')
plt.show()
非常感謝你。 我已經遇到這個問題好幾天了,但沒有發現錯誤。
也許有人知道如何以一種更簡單的方式來衡量PDF的功能。
我簡化了您的代碼,其輸出與您的代碼相同。 我認為它已經非常平滑,對數-對數圖中有一些非常尖銳的峰值,僅因為該曲線具有零點。 因此,它在對數-對數圖中不平滑,但在普通XY圖中則平滑。
import numpy as np
def gauss(r):
return np.exp(-((r-R0)**2)/(2*sigma**2))
def f(r,q):
return 3*(np.sin(q*r)-q*r*np.cos(q*r))/((r*q)**3)
R0=20
sigma=5
qm, rm = np.ogrid[0.001:2.0:0.005, 0.001:40:1000j]
gr = gauss(rm)
gr /= np.sum(gr)
fm = f(rm, qm)
fm *= gr
plot(qm.ravel(), fm.sum(axis=1)**2)
plt.yscale('log')
plt.xscale('log')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.