Goal
I'm trying to write code to compute the normalized Gaussian in the following,
$$ \begin{equation} \int_{-\infty}^{\infty} \frac{1}{ \sigma \sqrt{2 \pi}} \exp\bigg( - \frac{(x - \mu)^{2}}{2 \sigma^{2}}\bigg)dx \label{1} \tag{1} \end{equation} $$
where $\mu \in [-10,10]$
Problem
Unfortunately, the integration algorithm does not converge and throws the warning:
FinalStat.py:68: IntegrationWarning: The integral is probably divergent, or slowly convergent.
The Gaussian should be normalizing to $\eqref{1}$, it seems like their an issue with Quadpack's backend. I'd like to have a fix for this to get the integral to normalize to its proper value?
Code
from scipy.integrate import quad
import scipy.integrate as integrate
import numpy as np
import numpy
import random
import math
xvalues = []
yvalues = []
def generate():
#=================================================================== #
# #
# Generates Linear Data #
# a,b are random varibles #
# ================================================================== #
for i in range(0,10):
a = random.randint(-10, 10)
b = random.randint(-10, 10)
xvalues.append(i)
y = a * (b + i)
yvalues.append(y)
def weighted_mean(yvalues):
#=============================================#
# Computes the Weighted Mean #
#=============================================#
y_i = np.array(yvalues)
x_i = np.array(xvalues)
evaulated_mean = sum(x_i*y_i) / len(y_i)
return evaulated_mean
def weighted_variance(yvalues):
#============================================#
# Computes the Weighted Variance #
#============================================#
s = []
yvalues_mean = weighted_mean(yvalues)
for y in yvalues:
z = (y - yvalues_mean)**2
s.append(z)
#===================================#
#s_i = value of the data set #
#v_i = Number of Data Points in Pop #
#===================================#
s_i = np.array(s)
v_i = np.array(s)
t = (sum(s_i*v_i)/len(v_i))
print("The Variance", t)
return t
def gaussian(sigma,mu, x):
#===================================================#
#Define and Compute Gaussian Function with the FWDM #
#===================================================#
FWHM = 2*(numpy.sqrt(2*numpy.log(2)))*sigma
k = 1 / (sigma * math.sqrt(2*math.pi))
s = -1.0 / (2 * sigma * sigma)
def f(x):
return k * math.exp(s * (x - mu)*(x - mu))
print("The corresponding FHWM", FWHM)
print("The Integral is", quad(f, -np.inf, np.inf))
return FWHM
generate()
print( "The Mean is =>" , weighted_mean(yvalues))
#weighted_variance(yvalues)
print("our Normal Distrubtion Equals" , gaussian(weighted_variance(yvalues), weighted_mean(yvalues), random.randint(-10,10)))
Output
The Mean is => -53.7
The Variance 18538654.5401
The corresponding FHWM 43655195.3189315
FinalStat.py:68: IntegrationWarning: The integral is probably divergent, or slowly convergent.print("The Integral is", quad(f, -np.inf, np.inf))
The Integral is (-4.3038967971581716e-08, 6.997796078221529e-13)
our Normal Distrubtion Equals 43655195.3189315