为什么我不能 运行 我的 Regulafalsi 代码?由于 NoneType 错误

Why can't I run my Regulafalsi code? Because of NoneType error

这是我的一种寻根方法的代码。

from __future__ import division
def falseposition(f, a, b, imax=50, tolerance=1.0e-10):
  i = 0
  while i < imax:
    c = (a*f(b)-b*f(a))/(f(b) - f(a))
    if c == 0 or f(c) < tolerance:
      return c, i
    elif (f(a)*f(c))<0:
      b=c
    else:
      a=c
    i += 1
f = lambda x: x**5 - x + 1
root, steps = falseposition(f, 1, 8)
print ("The root is", root, "and the value is", f(root), "; steps taken:", steps)

存在类型错误。它说 'NoneType' 对象不可迭代。

如果您看到问题所在,请告诉。

您的 falseposition 函数 显式 return 当它找到满足条件 c 值时before i 变得大于 imax。如果没有,则它跳出 while 循环,到达函数体的末尾,然后(隐含地)returns None。在这种情况下,root, steps = falseposition(f, 1, 8) 语句实际上变为 root, steps = None,并且由于 None 不可迭代,您会收到此错误。

你这里主要有两种解决方案,要么:

return None, i 作为函数末尾的默认值(None 表示函数未能找到 c 的匹配值):

def falseposition(f, a, b, imax=50, tolerance=1.0e-10):
  i = 0
  while i < imax:
    c = (a*f(b)-b*f(a))/(f(b) - f(a))
    if c == 0 or f(c) < tolerance:
      return c, i
    elif (f(a)*f(c))<0:
      b=c
    else:
      a=c
    i += 1
  # nothing found
  return None, i

或者引发一些异常(并让调用者代码捕获它):

def falseposition(f, a, b, imax=50, tolerance=1.0e-10):
  i = 0
  while i < imax:
    c = (a*f(b)-b*f(a))/(f(b) - f(a))
    if c == 0 or f(c) < tolerance:
      return c, i
    elif (f(a)*f(c))<0:
      b=c
    else:
      a=c
    i += 1
  # nothing found
  raise ValueError("No matching c value")

这些解决方案中的哪一个有意义取决于上下文和诸如此类的东西,但显然在很多情况下可能找不到合适的 "solution" 第一个(returning ( None, i)`) 似乎是个不错的候选人。

您当然可以保留函数原样,并确保在尝试解压缩之前测试 return 值:

result = falseposition(f, 1, 8)
if result is None:
   print("oops, nothing found")
root, steps = result
# etc

但这真的很难看,而且实际上是不好的做法(人们期望函数的 return 值是一致的类型)。