-1

I wrote a python code to find root of 2*x-4 using bisection method



def func(x):
    return 2*x-4


def bisection(a,b):

    if (func(a) * func(b) >= 0):
        print("You have not assumed right a and b\n")
        return

    c = a
    while ((b-a) >= 0.01):

        
        c = (a+b)/2

        
        if (func(c) == 0.0):
            break

        
        if (func(c)*func(a) < 0):
            b = c
        else:
            a = c
            
    print("The value of root is : ","%.0f"%c)
    

a =-2
b = 4
bisection(a, b)

Now i want that the function input should be given by the user in the form of mx+n where m and n are integers. Can anyone help how can i do that ?

  • Can you elaborate on what exactly you are looking for? Are you looking for the code that can find the solution of ```f(x) = mx + n``` form using the bisection method? – Darshan P. Dec 04 '21 at 13:10
  • i have already given the code now i want the input of the function should be given by the user so how to do that ? – RAKSHIT HARSH Dec 04 '21 at 13:27

1 Answers1

1
m, n = list(map(int, input("Please enter the value of [m] [n] for f(x) = mx +n: ").split()))

def Input():
    a, b = list(map(int, input("Enter values of [a] [b]: ").split()))
    if f(a)*f(b)<0:
        Bisection(a, b)
    else:
        print("Oops! The root of function doesn't belong to the above domain\nPlease try to again:")
        Input()
        
def f(x):
    return m*x + n

def Bisection(a, b):
    c = (a+b)/2
    if f(c)*f(b)<0:
        Bisection(c, b)
    elif f(c)*f(a)<0:
        Bisection(c, a)
    elif f(c)==0:
        print(c)

Input()

See we know that Bisection, Newton-Raphson, or most of all Numerical methods are the iteration processes so better we use function inside of function: f(f(f(f.....) Of course! by checking the conditions.

Here, I have used elif f(c)==0 this is something which we can't use for quadratic/cubic or higher-order polynomials because getting the exact root will not be possible for all the types of equations say like f(x) = mx^2 - n where m, n > 0 However, we can define the iterations to be performed. By asking like Please enter the number of iterations to be performed:

Darshan P.
  • 192
  • 1
  • 9