Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Very new to Python
#1
This was copied from a book but gives several errors. Help!
from math import exp
def bisection(f,a,b,tol= 1e-3):
  if f(a)*f(b) > 0:
     print(f"No roots or more than one root in [{a},{b}]")
     return

     m = (a+b)/2

  while abs(f(m)) > tol:
     if f(a)*f(m) < 0:
        b = m
     else:
        a = m
        m = (a+b)/2
  return m

#call the method for f(x)= x**2-4*x+exp(-x)
f = lambda x: x**2-4*x+exp(-x)
sol = bisection(f,-0.5,1,1e-6)

print(f"x = {sol:g} is an approximate root, f({sol:g}) = {f(sol):g}")
Reply


Messages In This Thread
Very new to Python - by bliengme - Sep-24-2020, 12:36 PM
RE: Very new to Python - by snippsat - Sep-24-2020, 12:55 PM
RE: Very new to Python - by bliengme - Sep-25-2020, 01:31 AM

Forum Jump:

User Panel Messages

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