I'm working on my assignment where I must workout the bisection method on python. The algorithm looks correct in my eyes but when I run the code, I get a
TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
. Whats wrong and how can I fix this?
Q: Represent a polynomial p(x) = a0 + a1x + a2x2+⋯+anxn as a list of coefficients [a0,a1,…,an]. Write a function called poly_critical which takes 4 input parameters p, a, b and N where p is a Python list of numbers representing a polynomial p(x) , a and b are numbers defining an interval [a,b] and N is a positive integer.
The function poly_critical implements N iterations of the bisection method applied to the equation p′(x)=0 and returns an approximation of a critical point c where p′(c)=0 for c∈[a,b] .
For example, if p = [1,-1,1,0,0,1] (which represents p(x)=1−x+x2+x5 ), a=0, b=1 and N=10 then the function returns 0.4212656546685004 which approximates a solution of 5x4+2x−1=0 .
The function poly_critical may terminate in 4 ways:
If len(p) < 2
(p is linear), the function should print 'No critical points.' and return None.
If either initial endpoint is a critical point, return the endpoint.
If values at both endpoints and midpoint have the same sign at any iteration, the function should print 'Bisection method fails.' and return None.
The function implements N iterations of the bisection method successfully and returns the midpoint of the Nth subinterval.
My algorithm:
def poly_critical(p,a,b,N):
dp = [n*p[n] for n in range(1,len(p))]
if len(p) < 2:
print("No critical points")
return None
an = a
bn = b
def dP(x):
seq = [dp[i]*x**i for i in range(1,len(dp))]
sum_seq = sum(seq)
return sum_seq
if dP(an)*dP(bn) >= 0:
print("Bisection method fails.")
return None
if dP(an)*dP(bn) < 0:
mn = (an+bn)/2
for n in range(1,N+1):
mn = (an+bn)/2
if dP(mn)*dP(an) < 0:
an = an
bn = mn
elif dP(mn)*dP(bn) < 0:
an = mn
bn = bn
elif dP(mn) == 0:
return mn
else:
print("Bisection method fails.")
return None
return (an + bn)/2