Python用户输入方程式 [英] Python User input equation
问题描述
我正在编写一个简单的python脚本,以使用Eulers方法求解微分方程,现在,每次我想求解一个新方程时,我都必须更改源代码。
I'm writing a simple python script to solve differential equations using Eulers method and right now i have to change the source code every time i want to solve a new equation.
(由于这是一个个人项目,因此安全性目前不重要。)
(Safety isn't of any concern at the moment as this is a personal project.)
我的问题:
是否可以将方程式输入为用户输入并将其设为变量?例如,使用 e = input( enter equation)
,在其中输入 y / x
,然后使 e
一个变量供以后使用?
My question:
Would it be possible to type in an equation as user input and make it to a variable? For example, using e=input("enter equation")
where you enter y/x
, and making e
a variable for later use?
#I would like to be able to type in a equation as user input and turn it to a variable for later use in the if and elif segments, example
e=input("Enter your equation here")
e=float(e)
h=input("Ange steglängd: ")
h=float(h)
x=input("Angivet värde på x: ")
x=float(x)
y=input("Värde på y med anseende på x: ")
y=float(y)
z=input("Närmevärde du vill ha för y(x), ange x: ")
z=float(z)
if x<z:
while x<z:
#Type in equation below as e
e=y/x
y=y+h*e
x+=h
print(y)
elif x>z:
while x>z:
e=y/x
y=y-h*e
x-=h
print(y)
推荐答案
示例-这使我可以确定您需要什么。
Tack för exempel -- that allowed me to determine what you need.
是的,这是可能。以字符串变量形式读取方程式,例如
Yes, this is possible. Read in the equation as a string variable, such as
equation = input("Enter your equation here")
然后,当您要查找 e 的值时,请使用Python 评估方法:
Then when you want to find a value for e, use the Python eval method:
e = eval(equation)
使用此方法要非常小心: eval()
功能强大,并且非常接受它所接受的内容。
Be very careful with this method: eval()
is powerful, and very discriminating about what it accepts.
这篇关于Python用户输入方程式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!