我的任务是编写一个程序来执行分二的方法,以用6次迭代来解决SQRT(2)。这是我的代码。我无法沿途或结束时打印值,我不确定为什么。
import math
>>> def f(x):
return (x**2)-2
>>> def bisect (a,b,n):
while n < 6:
c=(a+b)/2
if f(c) == 0:
print [('Root is: ', c)]
elif f(a)*f(b) > 0:
b=c
n=(n+1)
print [('n: ',n,' c: ',c)]
else:
a=c
n=(n+1)
print [('n: ',n,' c: ',c)]
>>> print bisect (0,1,0)
SyntaxError: invalid syntax
>>> print bisect (0,1,0):
SyntaxError: invalid syntax
>>>
我立即看到两个问题。首先,在Python 3中,您需要在要打印的内容周围使用括号(即print(bisect(0,1,0))
)。这就是导致您的语法错误的原因。其次,除非您的凹痕是错误的,否则您的一分为二函数始于无限循环,因为它在N&lt时重复;6,但永远不会增加n。