Vectorize this with NumPy to avoid the need to loop:
import numpy as np
def gaussian(x, m, s):
fx = (1/((np.sqrt(2*np.pi))*s)*np.exp(-0.5*(((x - m)/s))**2))
return fx
m=0; s=1
x = np.linspace(m-5*s, m+5*s, num=100)
print(gaussian(x))
[ 1.48671951e-06 2.45106104e-06 3.99989037e-06 6.46116639e-06
1.03310066e-05 1.63509589e-05 2.56160812e-05 3.97238224e-05
6.09759040e-05 9.26476353e-05 1.39341123e-04 2.07440309e-04
3.05686225e-04 4.45889725e-04 6.43795498e-04 9.20104770e-04
1.30165384e-03 1.82273110e-03 2.52649578e-03 3.46643792e-03
4.70779076e-03 6.32877643e-03 8.42153448e-03 1.10925548e-02
1.44624148e-02 1.86646099e-02 2.38432745e-02 3.01496139e-02
3.77369231e-02 4.67541424e-02 5.73380051e-02 6.96039584e-02
8.36361772e-02 9.94771388e-02 1.17117360e-01 1.36486009e-01
1.57443188e-01 1.79774665e-01 2.03189836e-01 2.27323506e-01
2.51741947e-01 2.75953371e-01 2.99422683e-01 3.21590023e-01
3.41892294e-01 3.59786558e-01 3.74773979e-01 3.86422853e-01
3.94389234e-01 3.98433802e-01 3.98433802e-01 3.94389234e-01
3.86422853e-01 3.74773979e-01 3.59786558e-01 3.41892294e-01
3.21590023e-01 2.99422683e-01 2.75953371e-01 2.51741947e-01
2.27323506e-01 2.03189836e-01 1.79774665e-01 1.57443188e-01
1.36486009e-01 1.17117360e-01 9.94771388e-02 8.36361772e-02
6.96039584e-02 5.73380051e-02 4.67541424e-02 3.77369231e-02
3.01496139e-02 2.38432745e-02 1.86646099e-02 1.44624148e-02
1.10925548e-02 8.42153448e-03 6.32877643e-03 4.70779076e-03
3.46643792e-03 2.52649578e-03 1.82273110e-03 1.30165384e-03
9.20104770e-04 6.43795498e-04 4.45889725e-04 3.05686225e-04
2.07440309e-04 1.39341123e-04 9.26476353e-05 6.09759040e-05
3.97238224e-05 2.56160812e-05 1.63509589e-05 1.03310066e-05
6.46116639e-06 3.99989037e-06 2.45106104e-06 1.48671951e-06]
For a table:
import pandas as pd
pd.DataFrame({'x' : x, 'gauss' : gaussian(x)})
As for your comment:
my tutor said its a better idea to define x outside the function. If s
and m only exist inside the function, how can I reach them -- or
should I go about this in another way?
This depends mainly on whether you want x
to be a function of m
and s
. If that's always the case, then it is x
that you should incorporate into your function (defining x
locally in the function body):
def gaussian(m, s, num):
x = np.linspace(m-5*s, m+5*s, num=num)
fx = (1/((np.sqrt(2*np.pi))*s)*np.exp(-0.5*(((x - m)/s))**2))
return fx
Either way there is no need to deal with global
here and that's something you should probably avoid unless you have a very good reason for it.
The way things are set up in my first definition of gaussian
above, you are treating x
, m
, and s
as independent variables. That is, you could specify some other x
that doesn't depend on m
or s
. If you want x
to always be a function of m
and s
, then incorporate that directly into your function to avoid having to specify it outside of the function.