我对以下代码有疑问。它目前正在进行中,但我遇到的一个大问题是,无论我尝试过什么类型的输入,我的函数输入都会返回错误。如果我输入诸如 x 之类的函数,它要么返回错误类型的问题,要么返回未定义 x 的问题。
f = raw_input("Please enter function: y' = ")
x0 = float(raw_input("Please enter the initial x value: "))
y0 = float(raw_input("Please enter the initial y value: "))
xmax = float(raw_input("Please enter the value of x at which to approximate the solution: "))
h = float(raw_input("Please enter the step size: "))
showall = int(raw_input("Would you like to see all steps (1) or only the approximate solution (2)? "))
def f(x,y):
value = f
return (value)
def euler(x0,y0,h,xmax):
x=x0; y=y0; xd=[x0]; yd=[y0];
while x<xmax:
y = y + h*f(x,y)
yd.append(y)
x=x+h
xd.append(x)
return(xd,yd)
(xvals,yvals) = euler(x0,y0,h,xmax)
if showall == 1:
print ""
print "x_n y_n"
for uv in zip(xvals, yvals):
print uv[0],uv[1]
elif showall == 2:
print ""
print "x_n y_n"
print xvals, yvals
else:
print ""
print "There has been an error with your choice of what to see; showing all steps."
print ""
print "x_n y_n"
for uv in zip(xvals, yvals):
print uv[0],uv[1]
print " "
plotask = int(raw_input("Would you like to see a plot of the data? Yes (1); No (2) "))
if plotask == 1:
print "1"
elif plotask == 2:
pass
else:
print ""
print "Could not understand answer; showing plot."
任何帮助,将不胜感激。
错误和跟踪如下:
File "C:\Users\Daniel\Desktop\euler.py", line 25, in <module>
(xvals,yvals) = euler(x0,y0,h,xmax)
File "C:\Users\Daniel\Desktop\euler.py", line 19, in euler
y = y + h*f(x,y)
TypeError: unsupported operand type(s) for *: 'float' and 'function'