Python Forum
Very new to Python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Very new to Python (/thread-29880.html)



Very new to Python - bliengme - Sep-24-2020

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}")



RE: Very new to Python - snippsat - Sep-24-2020

(Sep-24-2020, 12:36 PM)bliengme Wrote: This was copied from a book but gives several errors. Help
You should post error(Traceback) you get,How to ask Smart Questions.
The problem here is that indentation is mess upped,have to be carful when copy from book/pdf then this can happen.
Here is a fix,indentation in Python is always 4-space.
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}")
Output:
x = 0.25 is an approximate root, f(0.25) = -0.158699



RE: Very new to Python - bliengme - Sep-25-2020

many thanks