我的任务是编写一个程序来执行二分法,以求解具有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
>>> 发布于 2017-03-01 12:30:13
我立即看到了两个问题。首先,在Python3中,您需要使用括号将您想要打印的内容(即print(bisect(0,1,0)))括起来。这就是导致语法错误的原因。其次,除非缩进错误,否则您的二等分函数将以无限循环开始,因为它会在n <6时重复,但不会增加n。
https://stackoverflow.com/questions/42523016
复制相似问题