【发布时间】:2017-07-15 21:52:22
【问题描述】:
我一直在尝试创建一个脚本,允许用户输入一个方程式并返回该方程式的根。但是我遇到了一个问题,我注意到在运行程序时它会接受输入并通过循环运行它,但它不会将变量分配给函数。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines
from matplotlib import style
from scipy.misc import derivative
import sympy as sp
symx = sp.Symbol('x')
def f(symx):
tmp = sp.sympify(input("Input your function here: "))
return tmp;
def fprime(symx):
tmp = sp.diff(f(symx))
return tmp;
def newtons_method(f, fprime, symx):
guess = int(input("Enter an initial guess: ")) # Convert to an int immediately.
for i in range(1,10):
nextGuess = guess - f(guess)/fprime(guess)
print(nextGuess)
guess = nextGuess
def main():
newtons_method(f, fprime, symx)
if __name__ == "__main__":
main()
这是脚本输出的内容;
Enter an initial guess: 2
Input your function here: 2*x**3 + 2*x**2
Input your function here: 2*x**3 + 2*x**2
2 - (2*x**3 + 2*x**2)/(6*x**2 + 4*x)
Input your function here: 2*x**3 + 2*x**2
Input your function here: 2*x**3 + 2*x**2
2 - 2*(2*x**3 + 2*x**2)/(6*x**2 + 4*x)
非常感谢您对改进的任何帮助,但您能否深入解释任何错误和改进,谢谢。
【问题讨论】:
-
你为什么要在
f(symx)中要求输入函数,在你让他们猜测之前你肯定想问函数吗? -
是的,这更合乎逻辑。我想我并没有真正考虑它,因为这不是我的主要问题,但我已经改变了它并且它解决了循环问题,但我仍然无法实现对根的分析解决方案。
标签: python python-3.x scipy sympy newtons-method