二分法 Jupyter Notebook
Bisection Method Jupyter Notebook
使用二分法求 f(x) = sqrt(x) - cos(x) 的 p3,我在纸上得到了正确答案 p3 = .625
我在转换问题并使用 Jupyter notebook 解决问题时遇到了问题。有什么建议吗?
Jupyter Notebook code
0.625是近似过程中的第三次猜测,所以for循环应该在第四次迭代之前完成,代码如下。
import math
##problem statement
#finding a root of f(x) = sqrt(x)-cos(x) between the interval [0,1]
#f(0) = -1 f(1) = 0.45969.. so there is at least one root between the interval [0,1]
a = 0
b = 1
maxIt = 100
negative_result = math.sqrt(a) - math.cos(a)
positive_result = math.sqrt(b) - math.cos(b)
for i in range(maxIt):
if i == 3:
print("answer is: ", guess)
break
guess = (a+b)/2
guess_result = math.sqrt(guess) - math.cos(guess)
if guess_result*negative_result >= 0:
a = guess
else:
b = guess
输出为
0.625
使用二分法求 f(x) = sqrt(x) - cos(x) 的 p3,我在纸上得到了正确答案 p3 = .625
我在转换问题并使用 Jupyter notebook 解决问题时遇到了问题。有什么建议吗?
Jupyter Notebook code
0.625是近似过程中的第三次猜测,所以for循环应该在第四次迭代之前完成,代码如下。
import math
##problem statement
#finding a root of f(x) = sqrt(x)-cos(x) between the interval [0,1]
#f(0) = -1 f(1) = 0.45969.. so there is at least one root between the interval [0,1]
a = 0
b = 1
maxIt = 100
negative_result = math.sqrt(a) - math.cos(a)
positive_result = math.sqrt(b) - math.cos(b)
for i in range(maxIt):
if i == 3:
print("answer is: ", guess)
break
guess = (a+b)/2
guess_result = math.sqrt(guess) - math.cos(guess)
if guess_result*negative_result >= 0:
a = guess
else:
b = guess
输出为
0.625