python - 在二分法中得到错误的输出
问题描述
我创建了以下执行二分法的代码。
我正在尝试使用它在区间 [1 , 3.1]。
我得到了一个提示,即 x_0 = 2 是该函数在区间上的根。我知道没有根,我希望有人能帮我解决这个问题!
下面是我的代码:
import math
import numpy as np
def root(x):
return (x**7-6*x**6-28*x**5+232*x**4-336*x**3-544*x**2+1728*x-1152)
def bisection_method(f, a, b, tol):
if f(a)*f(b) > 0:
#end function, no root.
print("No root found.")
else:
iter = 0
while (b - a)/2.0 > tol:
midpoint = (a + b)/2.0
if f(a)*f(midpoint) < 0: # Increasing but below 0 case
b = midpoint
else:
a = midpoint
iter += 1
return(midpoint, iter)
answer, iterations = bisection_method(root, 1, 3.1, 10**(-14))
print("Answer:", answer, "\nfound in", iterations, "iterations")
这是我得到的输出:
No root found.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-ecdc56120415> in <module>()
21 return(midpoint, iter)
22
---> 23 answer, iterations = bisection_method(root, 1, 3.1, 10**(-14))
24 print("Answer:", answer, "\nfound in", iterations, "iterations")
TypeError: 'NoneType' object is not iterable
解决方案
推荐阅读
- maven - 如何配置 pom.xml 以将 jooq 类生成到两个不同的包中?
- javascript - 从嵌套的对象数组中获取值
- c++ - 将项目设置为32位后找不到cout uint_32等
- python - 从别名导入时出现 ModuleNotFoundError
- javascript - 点击isso评论系统头像附近的“^”图标无法投票评论
- python - 无法导入 mysql.connector - ModuleNotFoundError:没有名为“mysql”的模块
- python - 数据帧中的多点(df['geometry'])键错误,但键存在。KeyError:13个geopandas
- numpy - 填充numpy数组而不循环所有索引
- javascript - 如何在使用 Selenide 自动化脚本时避免浏览器重定向?
- node.js - 在 NodeJS 应用程序上接收“连接被拒绝”以在 Windows 10 上进行外部连接