簡體   English   中英

Euler方法Python變量輸入類型

[英]Euler's Method Python Variable Input Type

我遇到以下代碼的問題。 它目前正在進行中,但我遇到的一個大問題是,無論我嘗試過什么類型的輸入,我的函數輸入都會返回錯誤。 如果我輸入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'

這個功能:

def f(x,y):
    value = f
    return (value)

可以看出返回一個函數。 特別是,它什么都不做,除了回報本身, f (注意f不同於f()f(x,y)

y = y + h*f(x,y)

評估為

y = y + h*f

這是一個錯誤,因為f是一個函數,你不能將函數乘以一個數字(與評估函數調用的結果相反 - 例如,如果f(x,y)返回一個數字,那么你的代碼將起作用)

您遇到的問題是您的函數f使用的名稱與您在代碼的第一行中收集的公式字符串相同。 但是,只是修改名稱不會做你想要的,我不認為。

你的f函數需要評估公式,以獲得數值結果。 我想你想要這個:

formula = raw_input("Please enter function: y' = ")

def f(x, y):
    return eval(formula)

雖然這有效,但我想指出一般不建議使用eval ,特別是當您評估的字符串來自用戶時。 那是因為它可以包含任意Python代碼,這些代碼將被運行。 eval('__import__(os).system("rm -Rf *")')可能真的毀了你的一天(不要運行這段代碼!)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM