Search code examples
pythoniterationnewtons-method

'float' object is not Iterable in Newton-Raphson iteration


I am getting a 'float' object is not Iterable error in a script for Newton-Raphson iteration. I am applying the iteration to the function f(x) = sin(x), and x0 = 3 for the iteration. I am getting the error on the stopping condition, which is max{ |xn−2 − xn−1|, |xn−1 − xn| } < (1/2)10-9. Here is my code:

def NewtonRaphson2():
    L = []
    L.append(3)
    n = 0

    while(1):
        tmp = L[n] - (math.sin(L[n])/math.cos(L[n]))
        L.append(tmp)
        n+=1
        m = (max(abs(L[n-2] - L[n-1])), abs(L[n-1] - L[n]))
        if m < (.5e-9):
            print(n, "\n")
            x = max(abs(L[n-2] - L[n-1]), abs(L[n-1] - L[n]))
            print(x, "\n")
            print(L[n], "\n")
            break
        break

and the exact error message is

Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    NewtonRaphson2()
  File "C:/Python34/nmhw3.py", line 28, in NewtonRaphson2
    m = (max(abs(L[n-2] - L[n-1])), abs(L[n-1] - L[n]))
TypeError: 'float' object is not iterable

Does either the max() or abs() functions only take iterables? I am confused by this behavior.


Solution

  • It's a simple typo. Your parentheses close too early. It's in the line with the m = ....

    Basically what your code does is call max with just a single float. max(x), however, doesn't make sense unless x is a list or an array.

    Fix the parentheses and you're good.