donut juice
donut juice

Reputation: 267

'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.

Upvotes: 1

Views: 181

Answers (2)

quizdog
quizdog

Reputation: 662

max( ) can take either an iterable or multiple arguments. This is shown in the first few lines of the help(max):

>>> help(max)
Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value

as Lagerbaer points out - if you fix your parentheses placement you will invoke max( ) with the second form - passing in multiple arguments. (extra non PEP 8 spaces added for emphasis!)

m = max(   abs(L[n-2] - L[n-1])  ,   abs(L[n-1] - L[n])   )

If you did want to invoke max( ) with the first form you could add parentheses to turn your two arguments into a single tuple which is then an iterable. The parentheses are superfluous but maybe you're a Lisp fan and miss all those parens! :-)

m = max( (  abs(L[n-2] - L[n-1])  ,   abs(L[n-1] - L[n]) )  )  

Upvotes: 0

cadolphs
cadolphs

Reputation: 9647

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.

Upvotes: 2

Related Questions