import sympy as sp
x = sp.Symbol('x')
# 定义表达式
expr1 = (x-1)*(x-2)*(x-3)*(x-4)
# 求解表达式的导数
derivative = expr1.diff(x).expand()
print(derivative)
def bisection(a, b, tol):
if expr1.diff(a) * expr1.diff(b) < 0:
print("存在实根")
else:
print("没有实根")
while (b - a) / 2 > tol:
c = (a + b) / 2
if expr1.diff(c) == 0:
return c
elif expr1.diff(c) * expr1.diff(a) < 0:
b = c
else:
a = c
return (a + b) / 2
a = sp.Symbol('a')
b = sp.Symbol('b')
tol = sp.Symbol('tol')
a = sp.sympify(1)
b = sp.sympify(4)
tol = sp.sympify(1e-6)
x1 = bisection(a, b, tol)
x2 = bisection(x1, b, tol)
x3 = bisection(a, x2, tol)
print("精确值:", x1, x2, x3)
我的做法就是先调用库求导,然后得出那个导数的式子,并且将其展开化简成一般形式,之后我想求出这个导数的根(二分法),但是无论怎么弄都没有正确,一直报错。提交时间已经过去了,我现在是事后回来想复盘一下是什么情况