簡體   English   中英

Python:數字和運算符串聯不起作用(Euler方法)

[英]Python: Number and operator concatenation not working (Euler's Method)

每當我運行以下(Python)代碼,嘗試使用Euler方法時,都會收到以下錯誤:

y + = h * eval(diff_eq_solved); TypeError:無法連接“ str”和“ float”對象。

該錯誤很容易理解,但是由於拆分中的所有項目都已轉換為字符串,因此我不確定問題出在哪里。 我的猜測是+運算符不包含在字符串中,但是我不確定如何解決(可能是轉義?)。 請幫忙!

x = raw_input("What is your initial x? ")

y = raw_input("What is your initial y? ")

h = float(raw_input("What is your step size? "))
final_x = float(raw_input("At what value of x would you like to approximate the solution? "))
diff_eq = raw_input("What is your differential equation? ")
split = list(diff_eq)

while float(x) < final_x:
    def replace(split, X, Y):
        i = 0
        for v in split:
            if v == X:
                split.pop(i)
                split.insert(i, Y)
            i += 1
    replace(split, "x", str(x))
    replace(split, "y", str(y))
    diff_eq_solved = ''.join(split)
    y += h * eval(diff_eq_solved)
    x += h

if type(y) != int:
    print "Syntax Error."

print y

您可以通過以下方法幫助自己回答此問題:

print type(y), type(h), type(eval(diff_eq_solved))

您會發現y的類型為str -raw_input的文檔說

然后,該函數從輸入中讀取一行,將其轉換為字符串(將尾隨換行符分隔),然后將其返回。

...因此您需要將其轉換為浮點數:

y=float(raw_input(prompt))

生成的程序如下所示:

x = float(raw_input("What is your initial x? "))

y = float(raw_input("What is your initial y? "))

h = float(raw_input("What is your step size? "))
final_x = float(raw_input("At what value of x would you like to approximate the solution? "))
diff_eq = raw_input("What is your differential equation? ")
split = list(diff_eq)

while float(x) < final_x:
    def replace(split, X, Y):
        i = 0
        for v in split:
            if v == X:
                split.pop(i)
                split.insert(i, Y)
            i += 1
    replace(split, "x", str(x))
    replace(split, "y", str(y))
    diff_eq_solved = ''.join(split)
    print type(y), type(h), type(eval(diff_eq_solved))
    y += h * eval(diff_eq_solved)
    x += h

if type(y) != int:
    print "Syntax Error."

print y

結果輸出如下所示:

(h2hh)~ mgregory$ python foo.py
What is your initial x? 0
What is your initial y? 1
What is your step size? 0.5
At what value of x would you like to approximate the solution? 6
What is your differential equation? x*y
<type 'float'> <type 'float'> <type 'float'>
<type 'float'> <type 'float'> <type 'float'>
<type 'float'> <type 'float'> <type 'float'>
<type 'float'> <type 'float'> <type 'float'>
<type 'float'> <type 'float'> <type 'float'>
<type 'float'> <type 'float'> <type 'float'>
<type 'float'> <type 'float'> <type 'float'>
<type 'float'> <type 'float'> <type 'float'>
<type 'float'> <type 'float'> <type 'float'>
<type 'float'> <type 'float'> <type 'float'>
<type 'float'> <type 'float'> <type 'float'>
<type 'float'> <type 'float'> <type 'float'>
Syntax Error.
1.0
(h2hh)~ mgregory$ 

暫無
暫無

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

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