Polynomials in python

2565 views python
0

In the following code in the function root(x) I am trying to return a polynomial but I am running into an error. Is there a way to use higher degree polynomial with coefficients?

import math
import numpy as np
def root(x):
    return(x**4+6x**2 -3)

def bisection_method(f, a, b, tol):
    if f(a)*f(b) > 0:
        #end function, no root.
        print("No root found.")
    else:
        iter = 0
        while (b - a)/2.0 > tol:
            midpoint = (a + b)/2.0

            if f(a)*f(midpoint) < 0: # Increasing but below 0 case
                b = midpoint
            else:
                a = midpoint

            iter += 1
        return(midpoint, iter)

answer, iterations = bisection_method(root, 1, 3.1, 10**(-14))
print("Answer:", answer, "\nfound in", iterations, "iterations")

Resulting in the following error,

 File "<ipython-input-22-a6a172c0ac5a>", line 4
    return(x**4+6x**2 -3)
             ^
SyntaxError: invalid syntax

answered question

you need another * after 6

yes you are correct, silly mistake, thanks!

Also the space between the 2 and the -3 is suspect, but I'm sure you've solved that by now :)

1 Answer

6

I think you are missing an * sign between 6 and x.

posted this

Have an answer?

JD

Please login first before posting an answer.