from math import pi, exp, sqrt
m = 0
s = 1
n = 10
min_value = m - 5*s
max_value = m + 5*s
dv = (max_value - min_value)/(n-1)
values = []
for i in range(n):
value = min_value + i*dv
values.append(value)
def gaussian2(values):
for x in values:
y = (1/(sqrt(2*pi)*s))*exp(-0.5*((x - m)/s)**2) # Formel
return y
print(y)
嗨,我正在尝试获取函数从表值中获取x值,但它不起作用。我无法打印列表值,因此我的功能一定有问题。有什么提示吗?
试过这个,这是一个好的解决方案吗?
from math import pi, exp, sqrt
m = 0
s = 2
n = 10
def gaussian2(m,s,x):
y = (1/(sqrt(2*pi)*s))*exp(-0.5*((x - m)/s)**2) # Formel
return y
min_value = m - 5*s
max_value = m + 5*s
dv = (max_value - min_value)/(n-1)
values = []
for i in range(n):
value = min_value + i*dv
values.append(value)
print(" x y")
for x in values:
y = gaussian2(m,s,x)
print("%5.1f %5.1f" % (x,y))
答案 0 :(得分:0)
这是怎么回事?
from math import pi, exp, sqrt
m = 0
s = 1
n = 10
min_value = m - 5*s
max_value = m + 5*s
dv = (max_value - min_value)/(n-1)
values = []
for i in range(n):
value = min_value + i*dv
values.append(value)
# print(values)
def gaussian2(vals, debug=True):
if type(vals) is list:
if debug:
print("input len = {0}".format(len(vals)))
y = []
t=0
for x in vals:
yi = (1/(sqrt(2*pi)*s))*exp(-0.5*((x - m)/s)**2) # Formel
y.append(yi)
t+=1
if debug:
print("{2}: x = {0}, y = {1}".format(x,yi,t))
return y
print(gaussian2(values))
答案 1 :(得分:0)
在print语句之前和循环内部的最后一个函数中有return语句。一旦到达return语句,循环就会停止运行。这种修改应该可以解决问题:
from math import pi, exp, sqrt
m = 0
s = 1
n = 10
min_value = m - 5*s
max_value = m + 5*s
dv = (max_value - min_value)/(n-1)
values = []
for i in range(n):
value = min_value + i*dv
values.append(value)
def gaussian2(values):
for x in values:
y = (1/(sqrt(2*pi)*s))*exp(-0.5*((x - m)/s)**2) # Formel
print(y)
return y
答案 2 :(得分:0)
更简单的解决方案是执行以下操作:
from math import pi, exp, sqrt
m = 0
s = 1
n = 10
min_value = m - 5*s
max_value = m + 5*s
dv = (max_value - min_value)/(n-1)
Xvalues = [min_value + i *dv for i in range(n)]
Yvalues = [1/(1/(sqrt(2*pi)*s))*exp(-0.5*((x - m)/s)**2) for x in Xvalues]
for y in Yvalues :
print(y);