TypeError: unsupported operand type(s) for *: ‘function’ and ‘function’ [closed]

I keep getting the error TypeError: unsupported operand type(s) for *: ‘function’ and ‘function’. It seems to think f1, fr, and f2 are functions. I’m not really sure what to do pretty new at Python

import math

def h(x):
    y = lambda x: x^2       #Define your function here
    return y

def fproot(xl, x2, es, maxiter):
    
    e =es + 1   #I needed to initialize e because it is not defined
    i = 0
    
    while e>=es and i < maxiter:
        
            e = lambda x: abs((x2-x1)/2)
            
            f1 = lambda x1: h(x1)
            f2 = lambda x2: h(x2)
            
            
            xr = lambda x: x2 - ((f2)*((x2-x1)/(f2-f1)))
            
            fr = lambda xr: h(xr)   #For the final loop
            
            a = (f1 * fr) #Test whether in the lower bound
            b = (f2 * fr) #Test whether in the upper bound
            
            if a>=0:
                x1 = xr
            if b>=0:
                x2 = xr
                x2=xr
            i+=1    #increases i each time until it matches maxiter
    
    print(xr)
    return xr, fr, i, e

result = fproot(0.5, 2, 0.01, 10)
print(result)

I’m not sure where to go from here.

  • 2

    f1 = lambda x1: h(x1) makes f1 a function. If you just want the value of h(x1), you just write f1 = h(x1).

    – 




  • If I do that I get “UnboundLocalError: cannot access local variable ‘x1’ where it is not associated with a value” Which I don’t understand because I’m passing x1 as an argument into the function.

    – 

  • 2

    @CodyHodges Your code shows a parameter named xl, not x1.

    – 

  • @MrDiamond, thank you… I can’t believe that was the issue holy cow bells! How did you see that so easy?

    – 

  • @CodyHodges, you may want to take a look at PEP 8 – Style Guide for Python Code. Using lowercase el in variable names is discouraged precisely because of these mistakes.

    – 




Leave a Comment