我正在研究一种使用牛顿法求解方程的代码。 它只能找到答案之一(根)。所以我尝试用x-answer除以方程,找到新方程的答案,这是初始方程的另一个答案,但是我得到了一个错误:
Traceback (most recent call last):
File "C:\Users\fathollahy\Desktop\w.py", line 26, in <module>
rt = f/WE
TypeError: unsupported operand type(s) for /: 'function' and 'Add'
这是我的代码:
from sympy import *
from random import randrange
x = Symbol('x')
T = input('Eqution: ')
f = eval(T)
f_prime = f.diff(x)
f = lambdify(x, f)
f_prime = lambdify(x, f_prime)
x = randrange(100)
print('attempts:')
while f(x) != 0:
D = f_prime(x)
F = f(x)
Q = F/D
x = x-Q
print(x)
else:
QW = x
print("answer:")
print(QW)
input()
x = Symbol('x')
WE = x-QW
rt = f/WE
rt_prime = rt.diff(x)
rt = lambdify(x, rt)
rt_prime = lambdify(x, rt_prime)
x = randrange(100)
print('attempts:')
while rt(x) != 0:
D = rt_prime(x)
F = rt(x)
Q = F/D
x = x-Q
print(x)
else:
QW = x
print("answer:")
print(QW)
input()
这段代码只能找到一个答案,并且效果很好(除了牛顿方法的缺点,如x ^(1/3):
from sympy import *
from random import randrange
x = Symbol('x')
T = input('Eqution: ')
f = eval(T)
f_prime = f.diff(x)
f = lambdify(x, f)
f_prime = lambdify(x, f_prime)
x = randrange(100)
print('attempts:')
while f(x) != 0:
D = f_prime(x)
F = f(x)
Q = F/D
x = x-Q
print(x)
else:
QW = x
print("answer:")
print(QW)
input()