0

i am trying to build a code that plot gauss distributions for diferent parameteres, but i am getting something wrong. I have wrote this code:

from numpy import zeros,empty,array,loadtxt,dot
import numpy as np
from math import log,exp,sin,cos,sqrt,pi,e,sqrt
from pylab import plot,show,ylim,ylabel,xlabel

n=10

#definindo os vetores posição e os vetores f que irão armazenar o valor da função no ponto.

f= zeros(n+1,float)
f1=zeros(n+1,float) 
f2= zeros(n+1,float)
f3= zeros(n+1,float)
x= zeros(n+1,float)

    
#Definindo a função gaussiana
    

def gauss(xi,xf,sig,a):
    step=(xf-xi)/n
    for k in range(n+1):
        f[k]=(1.0/(sqrt(2*pi)*sig))*exp((-(xi+step*k-a)**2)/(2*sig**2))     
        x[k]=xi+step*k
    print(f)
    return f



# A partir de agora iremos chamar a função gauss três vezes para plotar a função para diferentes valores dos parametros

f1=gauss(-5,5,5,0)

f2=gauss(-5,5,2,0)


plot(x,f1)
plot(x,f2)
show()

But when i plot the functions f1 and f2, i get the exact same graph.

1
  • In def gauss : *sig /sig = 1 So sig has no influence on the result Commented Apr 14, 2021 at 2:55

1 Answer 1

1

You have an aliasing problem with having your f and x lists be global. With the way you have it setup when you call plot(x, f2) you're essentially calling plot(x, f) because of the way you modify f in guass.

You can see this by running:

print('F1: ', f1)
f1 = gauss(-5, 5, 5, 0)
print('F1: ', f1)
print('F == F1: ', np.array_equal(f, f1))
f2 = gauss(-5, 5, 2, 0)
print('F1: ', f1)
print('F == F1: ', np.array_equal(f, f1))
print('F2 == F1: ', np.array_equal(f2, f1))
print('F2 == F: ', np.array_equal(f2, f))

Which produces

F1:  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
F1:  [0.04839414 0.05793831 0.06664492 0.07365403 0.07820854 0.07978846
 0.07820854 0.07365403 0.06664492 0.05793831 0.04839414]
F == F1:  True
F1:  [0.00876415 0.02699548 0.0647588  0.12098536 0.17603266 0.19947114
 0.17603266 0.12098536 0.0647588  0.02699548 0.00876415]
F == F1:  True
F2 == F1:  True
F2 == F:  True

By moving f and x to be initialized in your guass function and returning both, you should be getting the type of results you were expecting.

from math import exp, pi, sqrt

from numpy import zeros
from pylab import plot, show

n = 10


def gauss(xi, xf, sig, a):
    step = (xf - xi) / n
    f = zeros(n + 1, float)
    x = zeros(n + 1, float)
    for k in range(n + 1):
        f[k] = (1.0 / (sqrt(2 * pi) * sig)) * exp((-(xi + step * k - a) ** 2) / (2 * sig ** 2))
        x[k] = xi + step * k
    return x, f


x1, f1 = gauss(-5, 5, 5, 0)
x2, f2 = gauss(-5, 5, 2, 0)

plot(x1, f1)
show()
plot(x1, f2)
show()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.