-2

I have the problem of implementing these programs to find the root of a polynomial (bisection, regular falsi, raphson, secant), I want to make a menu to select the program that I want to execute but when I make the menu I do not get the menu as such only programs are executed.

# Defining Function
def f(x):
    return x**3-5*x-9

# Implementing Bisection Method
def bisection(x0,x1,e):
    step = 1
    print('\n\n*** BISECTION METHOD IMPLEMENTATION ***')
    condition = True
    while condition:
        x2 = (x0 + x1)/2
        print('Iteration-%d, x2 = %0.6f and f(x2) = %0.6f' % (step, x2, f(x2)))

        if f(x0) * f(x2) < 0:
            x1 = x2
        else:
            x0 = x2
        
        step = step + 1
        condition = abs(f(x2)) > e

    print('\nRequired Root is : %0.8f' % x2)


# Input Section
x0 = input('First Guess: ')
x1 = input('Second Guess: ')
e = input('Tolerable Error: ')

# Converting input to float
x0 = float(x0)
x1 = float(x1)
e = float(e)

#Note: You can combine above two section like this
# x0 = float(input('First Guess: '))
# x1 = float(input('Second Guess: '))
# e = float(input('Tolerable Error: '))


# Checking Correctness of initial guess values and bisecting
if f(x0) * f(x1) > 0.0:
    print('Given guess values do not bracket the root.')
    print('Try Again with different guess values.')
else:
    bisection(x0,x1,e)
    
#-------------------------
# Defining Function
def g(x):
    return x**3-5*x-9

# Implementing False Position Method
def falsePosition(x0,x1,e):
    step = 1
    print('\n\n*** FALSE POSITION METHOD IMPLEMENTATION ***')
    condition = True
    while condition:
        x2 = x0 - (x1-x0) * g(x0)/( g(x1) - g(x0) )
        print('Iteration-%d, x2 = %0.6f and f(x2) = %0.6f' % (step, x2, g(x2)))

        if g(x0) * g(x2) < 0:
            x1 = x2
        else:
            x0 = x2

        step = step + 1
        condition = abs(g(x2)) > e

    print('\nRequired root is: %0.8f' % x2)


# Input Section
x0 = input('First Guess: ')
x1 = input('Second Guess: ')
e = input('Tolerable Error: ')

# Converting input to float
x0 = float(x0)
x1 = float(x1)
e = float(e)

#Note: You can combine above two section like this
# x0 = float(input('First Guess: '))
# x1 = float(input('Second Guess: '))
# e = float(input('Tolerable Error: '))


# Checking Correctness of initial guess values and false positioning
if f(x0) * f(x1) > 0.0:
    print('Given guess values do not bracket the root.')
    print('Try Again with different guess values.')
else:
    falsePosition(x0,x1,e)
    
#---------------------------------------------
# Defining Function
def h(x):
    return x**3 - 5*x - 9

# Defining derivative of function
def hp(x):
    return 3*x**2 - 5

# Implementing Newton Raphson Method

def newtonRaphson(x0,e,N):
    print('\n\n*** NEWTON RAPHSON METHOD IMPLEMENTATION ***')
    step = 1
    flag = 1
    condition = True
    while condition:
        if g(x0) == 0.0:
            print('Divide by zero error!')
            break
        
        x1 = x0 - h(x0)/hp(x0)
        print('Iteration-%d, x1 = %0.6f and f(x1) = %0.6f' % (step, x1, h(x1)))
        x0 = x1
        step = step + 1
        
        if step > N:
            flag = 0
            break
        
        condition = abs(h(x1)) > e
    
    if flag==1:
        print('\nRequired root is: %0.8f' % x1)
    else:
        print('\nNot Convergent.')


# Input Section
x0 = input('Enter Guess: ')
e = input('Tolerable Error: ')
N = input('Maximum Step: ')

# Converting x0 and e to float
x0 = float(x0)
e = float(e)

# Converting N to integer
N = int(N)


#Note: You can combine above three section like this
# x0 = float(input('Enter Guess: '))
# e = float(input('Tolerable Error: '))
# N = int(input('Maximum Step: '))

# Starting Newton Raphson Method
newtonRaphson(x0,e,N)
#---------------------------------------
def i(x):
    return x**3 - 5*x - 9

# Implementing Secant Method

def secant(x0,i1,e,N):
    print('\n\n*** SECANT METHOD IMPLEMENTATION ***')
    step = 1
    condition = True
    while condition:
        if f(x0) == i(x1):
            print('Divide by zero error!')
            break
        
        x2 = x0 - (x1-x0)*i(x0)/( i(x1) - i(x0) ) 
        print('Iteration-%d, x2 = %0.6f and f(x2) = %0.6f' % (step, x2, i(x2)))
        x0 = x1
        x1 = x2
        step = step + 1
        
        if step > N:
            print('Not Convergent!')
            break
        
        condition = abs(i(x2)) > e
    print('\n Required root is: %0.8f' % x2)


# Input Section
x0 = input('Enter First Guess: ')
x1 = input('Enter Second Guess: ')
e = input('Tolerable Error: ')
N = input('Maximum Step: ')

# Converting x0 and e to float
x0 = float(x0)
x1 = float(x1)
e = float(e)

# Converting N to integer
N = int(N)


#Note: You can combine above three section like this
# x0 = float(input('Enter First Guess: '))
# x1 = float(input('Enter Second Guess: '))
# e = float(input('Tolerable Error: '))
# N = int(input('Maximum Step: '))

# Starting Secant Method
secant(x0,x1,e,N)


opcion = input(" Bienvenido a la calculadora de raices\n Seleccione el metodo a usar:\n 1-Biseccion\n 2-Regla Falsa\n 3-Newton Rapson\n 4-Secante\n")
print("El metodo a usar es: " + str(opcion)) #I use spanish :)
if opcion == 1: 
    f(x)
elif opcion == 2:
    g(x)
elif opcion == 3:
    h(x)
elif opcion == 3:
    i(x)

I'm just starting in python sorry if I don't know the basics

Thedark
  • 5
  • 3
  • 1
    All code that is not inside functions is executed when you run the program. So each block starting with comment `# Input Section` will be executed and only at the end, your menu code will. – treuss Nov 23 '22 at 12:46
  • The code I extract from https://www.codesansar.com/numerical-methods/secant-method-python-program.htm – Thedark Nov 23 '22 at 13:42

1 Answers1

2

Here is a (high level) solution to your problem:

  1. Create main function for your program. Check https://realpython.com/python-main-function/ for more info.
  2. Move input() functions and data conversions to the main function. This saves you a lot of copy/paste code. You then need to have the input functions and conversions only once in your code.
  3. Create a list (or dictionary) of the choices inside the main function e.g. choices = ['newtonRaphson', 'secant, ...]. A comprehensive description of data structures here: https://docs.python.org/3/tutorial/datastructures.html and if you are looking for a quick guide on list and dictionaries, check https://www.w3schools.com/python/python_lists.asp and https://www.w3schools.com/python/python_dictionaries.asp.
  4. Print the list of choices to the user. You can loop through the list and call print function for each list item. See example here: https://www.w3schools.com/python/python_lists_loop.asp
  5. Ask user input to choose the correct function e.g. the list index or dictionary key.
  6. Evaluate the input and call the appropriate function. This requires conditions, in other words if ... else statements. See more in here:https://www.w3schools.com/python/python_conditions.asp

I had difficulties adding the example code, but I can edit this later. Feel free to comment and ask questions!

riigs
  • 111
  • 8
  • I'm going to throw in a suggestion for using `pyinputplus.inputMenu()` to handle menu inputs, unless you want to practice handling user prompts. https://pyinputplus.readthedocs.io/en/latest/ – nigh_anxiety Nov 23 '22 at 13:34
  • oh that's a bit difficult for me for now :) I'll see it in more detail later – Thedark Nov 23 '22 at 13:45
  • And at some point, it is good to look into numpy https://numpy.org/ and Scipy https://scipy.org/ if you are going to work with numbers and algorithms a lot. I think the latter has your functions already implemented. But of course, some of the concepts in these python packages might be harder to grasp if you are lacking the basics of Python. So it is not a bad idea to implement the functions yourself at first to just learn the basics. – riigs Nov 23 '22 at 13:58
  • Will it be simpler if I make 4 separate .py files and one as main and choose which one to run? as I would do it? – Thedark Nov 23 '22 at 13:59
  • This discussion might be relevant to your question: https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-script-from-another-script. In my opinion the simplest way is to have separate functions and classes and call them in your main program (as suggested by many in that thread). Calling a program inside another program seems unnecessary in your case. You can read about function vs. program here: https://www.geeksforgeeks.org/difference-between-program-and-function/ – riigs Nov 23 '22 at 14:10