0

I have written a code to find the roots of an equation by bisection method.
I am trying to append my loop index and the difference between two solutions every iteration of the loop, but I am getting the error mentioned in the title of the question.

Also, I saw the answers to similar questions where people had already suggested to use the write method instead of calling it directly however, that just gives me an error saying that 'builtin_function_or_method' object has no attribute 'write'

My code:-

#Function to solve by bisection method
def bisection(f,a,b,fileName,tol = 10**-6):
    #making sure a is left of b
    if(a>b):
        temp = b
        b = a
        a = temp
    
    #Bracketing the roots
    a,b = bracketChecker(f,a,b)
    if((a,b) == False): return None

    #Checking if either of a or b is a root
    if(f(a)*f(b) == 0):
        if(f(a)==0):
            return a
        else: return b

    else:
        i = 0
        c = 0
        while(abs(a-b) > tol and i<200):
            c_old = c
            c = (a+b)/2.0
            abserr = c - c_old
            if (abs(f(c)) < tol):
                return c
            if (f(a)*f(c)<0):
                b = c
            else: a = c

            #Appending the data
            with open(fileName, 'a') as f:
                print(i,abserr, file=f)             #The error is occuring here
            i += 1
    return (a+b)/2.0
  • Hey, I can not reproduce your error but I notice you redefine variable "f". At first f is function passed to your arguments, then, f is a file object created by the open() function. Maybe, the line "print(i,abserr, file=f)" refer to the wrong f which is a built-in function ==> Python report the error 'builtin_function_or_method' object has no attribute 'write'. I suggest you can try rename your variable and see what happen? – mibu Oct 03 '20 at 07:45
  • Yeah, i am stupid. Thanx for pointing that out.... Changing f to something else works lmao... – Shashank Saumya Oct 03 '20 at 07:54

1 Answers1

0

It works fine, the problem was only occurring because i had named the file as f, which is the same variable i used for my function. Hence, the errors... Thank you @mibu for pointing that out

  • I am quite curious, why Python throw the error in the first place. Although you redefine your variable, variable redefinition is legal in Python (not a good practice though). So after line "with open(fileName, 'a') as f:", f should refer to the new file object not the old function => the line "print(i,abserr, file=f)" should not throw any error. What do you think? – mibu Oct 03 '20 at 12:11
  • Hmmm... I'm new to python so i dont really know.... – Shashank Saumya Oct 04 '20 at 13:03
  • FYI, I try your code myself and it work just fine. – mibu Oct 05 '20 at 15:38