牛顿-拉夫森方法用户输入和数值输出问题



我一直在尝试创建一个脚本,该脚本允许用户输入方程并返回该方程的根。但是,我遇到了一个问题,并且已经注意到,在运行程序时,它将获取输入并通过循环运行,但它没有将变量分配给函数。

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)

对改进的任何帮助都非常感谢,但是您还可以深入解释任何错误和改进,谢谢。

您不应该随时调用input函数,仅在初始时刻,除了不需要传递函数名称。

import sympy as sp
x = sp.symbols('x')
def f(symx):
    tmp = sp.sympify(symx)
    return tmp
def fprime(symx):
    tmp = sp.diff(f(symx))
    return tmp;
def newtons_method():   
    guess = sp.sympify(float(input("Enter an initial guess: "))) # Convert to an int immediately.
    symx = input("Input your function here: ")
    div = f(symx)/fprime(symx)
    for i in range(1, 10):
        print(guess.evalf())
        nextGuess = guess - div.subs(x, guess)
        guess = nextGuess

def main():
    newtons_method()
if __name__ == "__main__":
    main()

测试:

Enter an initial guess: 2
Input your function here: 2*x**3 + 2*x**2
2.00000000000000
1.25000000000000
0.760869565217391
0.448024718605164
0.254024574811046
0.138693453631666
0.0733275286119194
0.0378747932767810
0.0192767426403216
Enter an initial guess: 2
Input your function here: x**2-2
2.00000000000000
1.50000000000000
1.41666666666667
1.41421568627451
1.41421356237469
1.41421356237310
1.41421356237309
1.41421356237310
1.41421356237309

我不熟悉sympy模块,所以我用 .replace用猜测替换了 x,我使用 eval()来计算结果

这些是我更改的功能:

def f(value):
    eq1 = eq.replace("x", str(value))
    tmp = eval(eq1) # sympy uses eval anyway
    return tmp;
def fprime(value):
    eq2 = str(sp.diff(eq).replace("x", str(value)))
    tmp = eval(eq2) 
    return tmp;
def newtons_method(f, fprime, symx):
    global eq
    eq = input("Input your function here: ") # ask for function first :)
    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

这是给定的输出:

>>> 
Input your function here: x**2 - 16
Enter an initial guess: 3
4.166666666666667
4.003333333333333
4.000001387732445
4.000000000000241
4.0
4.0
4.0
4.0
4.0
>>> 

希望这对您有帮助:)

最新更新