Python Forum
Secant and Bisection method
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Secant and Bisection method
#1
#I am taking an online python class for fun. I have read ahead and this is one of the questions that I
#received. I have no idea where to begin. Any help?

Make a bisection and secant method code to allow it to solve a multi-dimensional function (MD function).
We will use the function f1 below to test your methods.
def f1(var):
x,y,z = var
return np.cos(y+x**2) + z

The values for the variables that are to remain constant and the two initial guesses for the variable of interest should be provided in your new MD-root-finder method in two lists (one list for each guess and constant values). If you require the two guesses to straddle the root, be sure that is specified in your dock string, and check to make sure they do. If they do not, stop the program and tell the user. If you wish, you could also have the user input which of the three variables should be solved for, or you could ascertain that from comparing the input initial guess lists. All inputs must be in the function call parenthesis “()” for your new root-finder method. Include the function f1 from above in the same file as the solver.

1. Solve for x at y=2.5,z=0.2. There is a root at x=1.4181. See if your solver finds it.

2. Solve for y at x=1.4,z=0.2. There is a root at y=2.5510. See if your solver finds it. [/i][/b]
Reply
#2
start by creating pseudo code.
refine until you have a clear view of how you think code should flow
Then search pypi.org for packages that might be needed.
start coding
Reply
#3
# This was the code I came up with for the bisection method. I guess I don't know where to go from
# here.
import math
import matplotlib.pyplot as plt


# Initialize the constants
k = 10
C = -1


def f(x):
    return x * math.sin(k * x) - x - C


def bisection(p1, p2):
    if (f(p1) * f(p2) >= 0):
        print("Wrong a and b\n")
        return

    p3 = p1
    while ((p2 - p1) >= 0.001):

        # Find middle point
        p3 = (p1 + p2) / 2

        # Check if middle point is root
        if (f(p3) == 0.0):
            break

        # Decide the side to repeat the steps
        if (f(p3) * f(p1) < 0):
            p2 = p3
        else:
            p1 = p3

    print("Root = ", "%.4f" % p3)


# Initial values assumed
a = 1.6
b = 2.1

bisection(a, b)
print(bisection(a,b))
Reply
#4
you should also take a look at numpy and scipy
a lot of math code is already written in these packages.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020