61A-025-Exceptions_1..

61A Lecture 25
Friday, October 28
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
5
3
1
9
7
11
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
5
3
1
9
7
11
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
5
3
9
1
7
11
Right!
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
5
3
9
1
7
11
Right!
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
8
5
9
3
9
7
1
7
11
11
Right!
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
8
5
9
3
9
7
1
7
Right!
11
11
Left!
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
8
8
5
9
7
3
9
7
1
7
Right!
11
11
Left!
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
8
8
5
9
7
3
9
7
1
7
Right!
11
None None
11
Left!
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
8
8
5
9
7
3
9
7
1
7
Right!
11
None None
11
Left!
Right!
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
8
8
8
5
9
7
None
3
9
7
1
7
Right!
11
None None
11
Left!
Right!
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
8
8
8
5
9
7
None
3
9
7
1
7
Right!
11
None None
11
Left!
Right!
Stop!
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
8
8
8
5
9
7
None
3
9
7
1
7
Right!
11
None None
11
Left!
Right!
Stop!
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
8
8
8
5
9
7
None
3
9
7
1
7
Right!
11
None None
11
Left!
Right!
Stop!
8
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
8
8
8
5
9
7
None
3
9
7
1
7
Right!
11
None None
11
Left!
Right!
Stop!
7
8
8
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
8
8
8
5
9
7
None
3
9
7
1
7
Right!
11
None None
11
Left!
Right!
Stop!
9
7
8
8
7
11
8
2
Friday, October 28, 2011
From Last Time: Adjoining to a Tree Set
8
8
8
8
5
9
7
None
3
9
7
1
7
11
None None
11
Right!
Left!
Right!
Stop!
5
9
7
8
3
1
8
9
7
7
11
11
8
8
2
Friday, October 28, 2011
From the Exam: Pruned Trees
a
b
c
d
3
Friday, October 28, 2011
From the Exam: Pruned Trees
a
pruned
b
c
d
(a,b)
(a,c)
(a,d)
True
True
False
3
Friday, October 28, 2011
From the Exam: Pruned Trees
a
c
4
Friday, October 28, 2011
From the Exam: Pruned Trees
a
c
pruned(a, c)
4
Friday, October 28, 2011
From the Exam: Pruned Trees
a
c
pruned(a, c)
4
Friday, October 28, 2011
From the Exam: Pruned Trees
a
c
pruned(a, c)
implies
4
Friday, October 28, 2011
From the Exam: Pruned Trees
a
c
pruned(a, c)
implies
pruned(a.right, c.right)
4
Friday, October 28, 2011
From the Exam: Pruned Trees
a
c
pruned(a, c)
implies
pruned(a.right, c.right)
4
Friday, October 28, 2011
From the Exam: Pruned Trees
a
c
pruned(a, c)
implies
pruned(a.right, c.right)
4
Friday, October 28, 2011
From the Exam: Pruned Trees
a
c
pruned(a, c)
implies
pruned(a.right, c.right)
4
Friday, October 28, 2011
From the Exam: Pruned Trees
a
c
pruned(a, c)
implies
pruned(a.right, c.right)
what about c.left?
4
Friday, October 28, 2011
From the Exam: Pruned Trees
a
pruned(a, c)
c
None
None
implies
None
None
pruned(a.right, c.right)
what about c.left?
4
Friday, October 28, 2011
From the Exam: Pruned Trees
a
pruned(a, c)
c
None
None
implies
None
None
pruned(a.right, c.right)
what about c.left?
4
Friday, October 28, 2011
From the Exam: Pruned Trees
a
5
Friday, October 28, 2011
From the Exam: Pruned Trees
a
pruned(a, d)
5
Friday, October 28, 2011
From the Exam: Pruned Trees
a
d
pruned(a, d)
5
Friday, October 28, 2011
From the Exam: Pruned Trees
a
d
pruned(a, d)
would imply
5
Friday, October 28, 2011
From the Exam: Pruned Trees
a
d
pruned(a, d)
would imply
pruned(a.left, d.left)
5
Friday, October 28, 2011
From the Exam: Pruned Trees
a
d
pruned(a, d)
would imply
pruned(a.left, d.left)
5
Friday, October 28, 2011
From the Exam: Pruned Trees
a
pruned(a, d)
d
None
would imply
pruned(a.left, d.left)
5
Friday, October 28, 2011
From the Exam: Pruned Trees
a
pruned(a, d)
d
None
would imply
pruned(a.left, d.left)
None
5
Friday, October 28, 2011
From the Exam: Pruned Trees
a
pruned(a, d)
d
None
would imply
pruned(a.left, d.left)
None
None
5
Friday, October 28, 2011
From the Exam: Pruned Trees
pruned(a, d)
a
d
None
Not None
None
would imply
pruned(a.left, d.left)
None
5
Friday, October 28, 2011
From the Exam: Pruned Trees
a
b
c
d
6
Friday, October 28, 2011
From the Exam: Pruned Trees
a
b
c
d
Recursive call: both branches are pruned as well
6
Friday, October 28, 2011
From the Exam: Pruned Trees
a
b
c
d
Recursive call: both branches are pruned as well
Base cases: one (or more) of the trees is None
6
Friday, October 28, 2011
From the Exam: Pruned Trees
a
b
c
d
Recursive call: both branches are pruned as well
Base cases: one (or more) of the trees is None
def pruned(t1, t2):
6
Friday, October 28, 2011
From the Exam: Pruned Trees
a
b
c
d
Recursive call: both branches are pruned as well
Base cases: one (or more) of the trees is None
def pruned(t1, t2):
if t2 is None:
6
Friday, October 28, 2011
From the Exam: Pruned Trees
a
b
c
d
Recursive call: both branches are pruned as well
Base cases: one (or more) of the trees is None
def pruned(t1, t2):
if t2 is None:
return True
6
Friday, October 28, 2011
From the Exam: Pruned Trees
a
b
c
d
Recursive call: both branches are pruned as well
Base cases: one (or more) of the trees is None
def pruned(t1, t2):
if t2 is None:
return True
if t1 is None:
6
Friday, October 28, 2011
From the Exam: Pruned Trees
a
b
c
d
Recursive call: both branches are pruned as well
Base cases: one (or more) of the trees is None
def pruned(t1, t2):
if t2 is None:
return True
if t1 is None:
return False
6
Friday, October 28, 2011
From the Exam: Pruned Trees
a
b
c
d
Recursive call: both branches are pruned as well
Base cases: one (or more) of the trees is None
def pruned(t1, t2):
if t2 is None:
return True
if t1 is None:
return False
return pruned(t1.left, t2.left) and pruned(t1.right, t2.right)
6
Friday, October 28, 2011
Today's Topic: Handling Errors
7
Friday, October 28, 2011
Today's Topic: Handling Errors
Sometimes, computers don't do exactly what we expect
7
Friday, October 28, 2011
Today's Topic: Handling Errors
Sometimes, computers don't do exactly what we expect
•
A function receives unexpected argument types
7
Friday, October 28, 2011
Today's Topic: Handling Errors
Sometimes, computers don't do exactly what we expect
•
•
A function receives unexpected argument types
Some resource (such as a file) does not exist
7
Friday, October 28, 2011
Today's Topic: Handling Errors
Sometimes, computers don't do exactly what we expect
•
•
•
A function receives unexpected argument types
Some resource (such as a file) does not exist
Network connections are lost
7
Friday, October 28, 2011
Today's Topic: Handling Errors
Sometimes, computers don't do exactly what we expect
•
•
•
A function receives unexpected argument types
Some resource (such as a file) does not exist
Network connections are lost
Grace Hopper's Notebook, 1947, Moth found in a Mark II Computer
7
Friday, October 28, 2011
Different Error Handling Policies
8
Friday, October 28, 2011
Different Error Handling Policies
8
Friday, October 28, 2011
Different Error Handling Policies
Versus
8
Friday, October 28, 2011
Different Error Handling Policies
Versus
8
Friday, October 28, 2011
Exceptions
9
Friday, October 28, 2011
Exceptions
A built-in mechanism in a programming language to declare and
respond to exceptional conditions
9
Friday, October 28, 2011
Exceptions
A built-in mechanism in a programming language to declare and
respond to exceptional conditions
Python raises an exception whenever an error occurs
9
Friday, October 28, 2011
Exceptions
A built-in mechanism in a programming language to declare and
respond to exceptional conditions
Python raises an exception whenever an error occurs
Exceptions can be handled by the program, preventing a crash
9
Friday, October 28, 2011
Exceptions
A built-in mechanism in a programming language to declare and
respond to exceptional conditions
Python raises an exception whenever an error occurs
Exceptions can be handled by the program, preventing a crash
Unhandled exceptions will cause Python to halt execution
9
Friday, October 28, 2011
Exceptions
A built-in mechanism in a programming language to declare and
respond to exceptional conditions
Python raises an exception whenever an error occurs
Exceptions can be handled by the program, preventing a crash
Unhandled exceptions will cause Python to halt execution
Mastering exceptions:
9
Friday, October 28, 2011
Exceptions
A built-in mechanism in a programming language to declare and
respond to exceptional conditions
Python raises an exception whenever an error occurs
Exceptions can be handled by the program, preventing a crash
Unhandled exceptions will cause Python to halt execution
Mastering exceptions:
Exceptions are objects! They have classes with constructors.
9
Friday, October 28, 2011
Exceptions
A built-in mechanism in a programming language to declare and
respond to exceptional conditions
Python raises an exception whenever an error occurs
Exceptions can be handled by the program, preventing a crash
Unhandled exceptions will cause Python to halt execution
Mastering exceptions:
Exceptions are objects! They have classes with constructors.
They enable non-local continuations of control:
9
Friday, October 28, 2011
Exceptions
A built-in mechanism in a programming language to declare and
respond to exceptional conditions
Python raises an exception whenever an error occurs
Exceptions can be handled by the program, preventing a crash
Unhandled exceptions will cause Python to halt execution
Mastering exceptions:
Exceptions are objects! They have classes with constructors.
They enable non-local continuations of control:
If f calls g and g calls h, exceptions can shift control from
h to f without waiting for g to return.
9
Friday, October 28, 2011
Exceptions
A built-in mechanism in a programming language to declare and
respond to exceptional conditions
Python raises an exception whenever an error occurs
Exceptions can be handled by the program, preventing a crash
Unhandled exceptions will cause Python to halt execution
Mastering exceptions:
Exceptions are objects! They have classes with constructors.
They enable non-local continuations of control:
If f calls g and g calls h, exceptions can shift control from
h to f without waiting for g to return.
However, exception handling tends to be slow.
9
Friday, October 28, 2011
Assert Statements
Assert statements raise an exception of type AssertionError
10
Friday, October 28, 2011
Assert Statements
Assert statements raise an exception of type AssertionError
assert <expression>, <string>
10
Friday, October 28, 2011
Assert Statements
Assert statements raise an exception of type AssertionError
assert <expression>, <string>
Assertions are designed to be used liberally and then disabled
in "production" systems. "O" stands for optimized.
10
Friday, October 28, 2011
Assert Statements
Assert statements raise an exception of type AssertionError
assert <expression>, <string>
Assertions are designed to be used liberally and then disabled
in "production" systems. "O" stands for optimized.
python3 -O
10
Friday, October 28, 2011
Assert Statements
Assert statements raise an exception of type AssertionError
assert <expression>, <string>
Assertions are designed to be used liberally and then disabled
in "production" systems. "O" stands for optimized.
python3 -O
Whether assertions are enabled is governed by a bool __debug__
10
Friday, October 28, 2011
Assert Statements
Assert statements raise an exception of type AssertionError
assert <expression>, <string>
Assertions are designed to be used liberally and then disabled
in "production" systems. "O" stands for optimized.
python3 -O
Whether assertions are enabled is governed by a bool __debug__
Demo
10
Friday, October 28, 2011
Raise Statements
11
Friday, October 28, 2011
Raise Statements
Exceptions are raised with a raise statement.
11
Friday, October 28, 2011
Raise Statements
Exceptions are raised with a raise statement.
raise <expression>
11
Friday, October 28, 2011
Raise Statements
Exceptions are raised with a raise statement.
raise <expression>
<expression> must evaluate to an exception instance or class.
11
Friday, October 28, 2011
Raise Statements
Exceptions are raised with a raise statement.
raise <expression>
<expression> must evaluate to an exception instance or class.
Exceptions are constructed like any other object; they are
just instances of classes that inherit from BaseException.
11
Friday, October 28, 2011
Raise Statements
Exceptions are raised with a raise statement.
raise <expression>
<expression> must evaluate to an exception instance or class.
Exceptions are constructed like any other object; they are
just instances of classes that inherit from BaseException.
TypeError -- A function was passed the wrong number/type of argument
11
Friday, October 28, 2011
Raise Statements
Exceptions are raised with a raise statement.
raise <expression>
<expression> must evaluate to an exception instance or class.
Exceptions are constructed like any other object; they are
just instances of classes that inherit from BaseException.
TypeError -- A function was passed the wrong number/type of argument
NameError -- A name wasn't found
11
Friday, October 28, 2011
Raise Statements
Exceptions are raised with a raise statement.
raise <expression>
<expression> must evaluate to an exception instance or class.
Exceptions are constructed like any other object; they are
just instances of classes that inherit from BaseException.
TypeError -- A function was passed the wrong number/type of argument
NameError -- A name wasn't found
KeyError -- A key wasn't found in a dictionary
11
Friday, October 28, 2011
Raise Statements
Exceptions are raised with a raise statement.
raise <expression>
<expression> must evaluate to an exception instance or class.
Exceptions are constructed like any other object; they are
just instances of classes that inherit from BaseException.
TypeError -- A function was passed the wrong number/type of argument
NameError -- A name wasn't found
KeyError -- A key wasn't found in a dictionary
RuntimeError -- Catch-all for troubles during interpretation
11
Friday, October 28, 2011
Try Statements
12
Friday, October 28, 2011
Try Statements
Try statements handle exceptions
12
Friday, October 28, 2011
Try Statements
Try statements handle exceptions
try:
<try suite>
except <exception class> as <name>:
<except suite>
...
12
Friday, October 28, 2011
Try Statements
Try statements handle exceptions
try:
<try suite>
except <exception class> as <name>:
<except suite>
...
Execution rule:
12
Friday, October 28, 2011
Try Statements
Try statements handle exceptions
try:
<try suite>
except <exception class> as <name>:
<except suite>
...
Execution rule:
The <try suite> is executed first;
12
Friday, October 28, 2011
Try Statements
Try statements handle exceptions
try:
<try suite>
except <exception class> as <name>:
<except suite>
...
Execution rule:
The <try suite> is executed first;
If, during the course of executing the <try suite>,
an exception is raised that is not handled otherwise, and
12
Friday, October 28, 2011
Try Statements
Try statements handle exceptions
try:
<try suite>
except <exception class> as <name>:
<except suite>
...
Execution rule:
The <try suite> is executed first;
If, during the course of executing the <try suite>,
an exception is raised that is not handled otherwise, and
If the class of the exception inherits from <exception class>, then
12
Friday, October 28, 2011
Try Statements
Try statements handle exceptions
try:
<try suite>
except <exception class> as <name>:
<except suite>
...
Execution rule:
The <try suite> is executed first;
If, during the course of executing the <try suite>,
an exception is raised that is not handled otherwise, and
If the class of the exception inherits from <exception class>, then
The <except suite> is executed, with <name> bound to the exception
12
Friday, October 28, 2011
Handling Exceptions
13
Friday, October 28, 2011
Handling Exceptions
Exception handling can prevent a program from terminating
13
Friday, October 28, 2011
Handling Exceptions
Exception handling can prevent a program from terminating
>>> try:
13
Friday, October 28, 2011
Handling Exceptions
Exception handling can prevent a program from terminating
>>> try:
x = 1/0
13
Friday, October 28, 2011
Handling Exceptions
Exception handling can prevent a program from terminating
>>> try:
x = 1/0
except ZeroDivisionError as e:
13
Friday, October 28, 2011
Handling Exceptions
Exception handling can prevent a program from terminating
>>> try:
x = 1/0
except ZeroDivisionError as e:
print('handling a', type(e))
13
Friday, October 28, 2011
Handling Exceptions
Exception handling can prevent a program from terminating
>>> try:
x = 1/0
except ZeroDivisionError as e:
print('handling a', type(e))
x = 0
13
Friday, October 28, 2011
Handling Exceptions
Exception handling can prevent a program from terminating
>>> try:
x = 1/0
except ZeroDivisionError as e:
print('handling a', type(e))
x = 0
handling a <class 'ZeroDivisionError'>
13
Friday, October 28, 2011
Handling Exceptions
Exception handling can prevent a program from terminating
>>> try:
x = 1/0
except ZeroDivisionError as e:
print('handling a', type(e))
x = 0
handling a <class 'ZeroDivisionError'>
>>> x
13
Friday, October 28, 2011
Handling Exceptions
Exception handling can prevent a program from terminating
>>> try:
x = 1/0
except ZeroDivisionError as e:
print('handling a', type(e))
x = 0
handling a <class 'ZeroDivisionError'>
>>> x
0
13
Friday, October 28, 2011
Handling Exceptions
Exception handling can prevent a program from terminating
>>> try:
x = 1/0
except ZeroDivisionError as e:
print('handling a', type(e))
x = 0
handling a <class 'ZeroDivisionError'>
>>> x
0
Multiple try statements: Control jumps to the except
suite of the most recent try statement that handles
that type of exception.
13
Friday, October 28, 2011
Handling Exceptions
Exception handling can prevent a program from terminating
>>> try:
x = 1/0
except ZeroDivisionError as e:
print('handling a', type(e))
x = 0
handling a <class 'ZeroDivisionError'>
>>> x
0
Multiple try statements: Control jumps to the except
suite of the most recent try statement that handles
that type of exception.
Demo
13
Friday, October 28, 2011
WWPD: What Would Python Do?
How will the Python interpreter respond?
14
Friday, October 28, 2011
WWPD: What Would Python Do?
How will the Python interpreter respond?
14
Friday, October 28, 2011
WWPD: What Would Python Do?
How will the Python interpreter respond?
def invert(x):
result = 1/x # Raises a ZeroDivisionError if x is 0
print('Never printed if x is 0')
return result
def invert_safe(x):
try:
return invert(x)
except ZeroDivisionError as e:
return str(e)
14
Friday, October 28, 2011
WWPD: What Would Python Do?
How will the Python interpreter respond?
def invert(x):
result = 1/x # Raises a ZeroDivisionError if x is 0
print('Never printed if x is 0')
return result
def invert_safe(x):
try:
return invert(x)
except ZeroDivisionError as e:
return str(e)
>>> invert_safe(1/0)
14
Friday, October 28, 2011
WWPD: What Would Python Do?
How will the Python interpreter respond?
def invert(x):
result = 1/x # Raises a ZeroDivisionError if x is 0
print('Never printed if x is 0')
return result
def invert_safe(x):
try:
return invert(x)
except ZeroDivisionError as e:
return str(e)
>>> invert_safe(1/0)
>>> try:
invert_safe(0)
except ZeroDivisionError as e:
print('Handled!')
14
Friday, October 28, 2011
WWPD: What Would Python Do?
How will the Python interpreter respond?
def invert(x):
result = 1/x # Raises a ZeroDivisionError if x is 0
print('Never printed if x is 0')
return result
def invert_safe(x):
try:
return invert(x)
except ZeroDivisionError as e:
return str(e)
>>> invert_safe(1/0)
>>> try:
invert_safe(0)
except ZeroDivisionError as e:
print('Handled!')
>>> inverrrrt_safe(1/0)
14
Friday, October 28, 2011
Example: Safe Iterative Improvement
15
Friday, October 28, 2011
Example: Safe Iterative Improvement
Iterative improvement is a higher-order function
15
Friday, October 28, 2011
Example: Safe Iterative Improvement
Iterative improvement is a higher-order function
• The update argument provides better guesses
15
Friday, October 28, 2011
Example: Safe Iterative Improvement
Iterative improvement is a higher-order function
• The update argument provides better guesses
• The done argument indicates completion
15
Friday, October 28, 2011
Example: Safe Iterative Improvement
Iterative improvement is a higher-order function
• The update argument provides better guesses
• The done argument indicates completion
• Used to implement Newton's method (find_root)
15
Friday, October 28, 2011
Example: Safe Iterative Improvement
Iterative improvement is a higher-order function
• The update argument provides better guesses
• The done argument indicates completion
• Used to implement Newton's method (find_root)
15
Friday, October 28, 2011
return find_root(lambda y: y * y é x)
def cube_root_newton(x):
Example:
Safe
"""Return
the Iterative
cube rootImprovement
of x.
>>> cube_root_newton(27)
3.0
Iterative
improvement is a higher-order function
"""
return
find_root(lambda
y: y *
y * y guesses
é x)
update
argument provides
better
• The
def
approx_derivative(f,
x, delta=1eé5):
done argument indicates
completion
• The
"""Return an approximation to the derivative of f at x."""
df =tof(x
+ delta) Newton's
é f(x)
implement
method (find_root)
• Used
return df/delta
def newton_update(f):
"""Return an update function for f using Newton's method."""
def update(x):
return x é f(x) / approx_derivative(f, x)
return update
def find_root(f, guess=1):
"""Return a guess of a zero of the function f, near guess.
>>> from math import sin
>>> find_root(lambda y: sin(y), 3)
3.141592653589793
"""
return iter_improve(newton_update(f), lambda x: f(x) == 0, guess)
@main
def run():
interact()
Friday, October 28, 2011
15
"""
return find_root(lambda y: y * y é x)
return find_root(lambda y: y * y é x)
def cube_root_newton(x):
def
cube_root_newton(x):
Example:
Safe
"""Return
the Iterative
cube rootImprovement
of x.
"""Return the cube root of x.
>>> cube_root_newton(27)
>>>
3.0 cube_root_newton(27)
Iterative
improvement is a higher-order function
3.0
"""
"""
return
find_root(lambda
y: y *
y * y guesses
é x)
update
argument
provides
better
• The
return find_root(lambda y: y * y * y é x)
def
approx_derivative(f,
x, delta=1eé5):
done argument indicates
completion
• The
def approx_derivative(f,
x,
delta=1eé5):
"""Return an approximation to the derivative of f at x."""
"""Return
approximation
to the derivative
of f at x."""
df =tof(x
+an
delta)
é f(x)
implement
Newton's
method
(find_root)
• Used
df
= f(x
+ delta) é f(x)
return
df/delta
return df/delta
def newton_update(f):
def newton_update(f):
"""Return an update function for f using Newton's method."""
"""Return
an update function for f using Newton's method."""
def update(x):
def update(x):
return x é f(x) / approx_derivative(f, x)
return
x é f(x) / approx_derivative(f, x)
return
update
return update
def find_root(f, guess=1):
def find_root(f,
guess=1):
"""Return a guess
of a zero of the function f, near guess.
"""Return a guess of a zero of the function f, near guess.
>>> from math import sin
>>>
math import sin
>>> from
find_root(lambda
y: sin(y), 3)
>>>
find_root(lambda y: sin(y), 3)
3.141592653589793
3.141592653589793
"""
"""
return iter_improve(newton_update(f), lambda x: f(x) == 0, guess)
return iter_improve(newton_update(f), lambda x: f(x) == 0, guess)
@main
@main
def run():
15
def run():
interact()
interact()
Friday, October 28, 2011
"""
return find_root(lambda y: y * y é x)
return find_root(lambda y: y * y é x)
def cube_root_newton(x):
def
cube_root_newton(x):
Example:
Safe
"""Return
the Iterative
cube rootImprovement
of x.
"""Return the cube root of x.
>>> cube_root_newton(27)
>>>
3.0 cube_root_newton(27)
Iterative
improvement is a higher-order function
3.0
"""
"""
return
find_root(lambda
y: y *
y * y guesses
é x)
update
argument
provides
better
• The
return find_root(lambda y: y * y * y é x)
def
approx_derivative(f,
x, delta=1eé5):
done argument indicates
completion
• The
def approx_derivative(f,
x,
delta=1eé5):
"""Return an approximation to the derivative of f at x."""
"""Return
approximation
to the derivative
of f at x."""
df =tof(x
+an
delta)
é f(x)
implement
Newton's
method
(find_root)
• Used
df
= f(x
+ delta) é f(x)
return
df/delta
return df/delta
def newton_update(f):
def newton_update(f):
"""Return an update function for f using Newton's method."""
"""Return
an update function for f using Newton's method."""
def update(x):
def update(x):
return x é f(x) / approx_derivative(f, x)
return
x é f(x) / approx_derivative(f, x)
return
update
return update
def find_root(f, guess=1):
def find_root(f,
guess=1):
"""Return a guess
of a zero of the function f, near guess.
"""Return a guess of a zero of the function f, near guess.
>>> from math import sin
>>>
math import sin
>>> from
find_root(lambda
y: sin(y), 3)
>>>
find_root(lambda y: sin(y), 3)
3.141592653589793
3.141592653589793
"""
"""
return iter_improve(newton_update(f), lambda x: f(x) == 0, guess)
return iter_improve(newton_update(f), lambda x: f(x) == 0, guess)
@main
@main
def run():
15
def run():
interact()
interact()
Friday, October 28, 2011
"""
return find_root(lambda y: y * y é x)
return find_root(lambda y: y * y é x)
def cube_root_newton(x):
def
cube_root_newton(x):
Example:
Safe
"""Return
the Iterative
cube rootImprovement
of x.
"""Return the cube root of x.
>>> cube_root_newton(27)
>>>
3.0 cube_root_newton(27)
Iterative
improvement is a higher-order function
3.0
"""
"""
return
find_root(lambda
y: y *
y * y guesses
é x)
update
argument
provides
better
• The
return find_root(lambda y: y * y * y é x)
def
approx_derivative(f,
x, delta=1eé5):
done argument indicates
completion
• The
def approx_derivative(f,
x,
delta=1eé5):
"""Return an approximation to the derivative of f at x."""
"""Return
approximation
to the derivative
of f at x."""
df =tof(x
+an
delta)
é f(x)
implement
Newton's
method
(find_root)
• Used
df
= f(x
+ delta) é f(x)
return
df/delta
return df/delta
def newton_update(f):
def newton_update(f):
"""Return an update function for f using Newton's method."""
"""Return
an update function for f using Newton's method."""
def update(x):
def update(x):
return x é f(x) / approx_derivative(f, x)
return
x é f(x) / approx_derivative(f, x)
return
update
return update
def find_root(f, guess=1):
def find_root(f,
guess=1):
"""Return a guess
of a zero of the function f, near guess.
"""Return a guess of a zero of the function f, near guess.
>>> from math import sin
>>>
math import sin
>>> from
find_root(lambda
y: sin(y), 3)
>>>
find_root(lambda y: sin(y), 3)
3.141592653589793
3.141592653589793
"""
"""
return iter_improve(newton_update(f), lambda x: f(x) == 0, guess)
return iter_improve(newton_update(f), lambda x: f(x) == 0, guess)
@main
@main
def run():
15
def run():
interact()
interact()
Friday, October 28, 2011
Bonus
Material
Exception Chaining
The except suite of a try statement can raise another
exception that adds additional information.
Demo
16
Friday, October 28, 2011