Question
*FILL IN WHERE IT STATES #YOUR CODE HERE PLEASE* We have not yet implemented a way to take derivatives of Power expressions, that
*FILL IN WHERE IT STATES " #YOUR CODE HERE " PLEASE*
We have not yet implemented a way to take derivatives of Power expressions, that is, expressions involving exponentiation. As we saw during lecture, here's the definition of the derivative of an expression with respect to :
To translate this into code, we need Logarithm to be one of our operators. Without it, the set of symbolic expressions would not be closed with respect to symbolic differentiation. We'd better add Logarithm to our collection of operators, and define a way to take the derivative of Logarithm expressions, too.
Using
we define Logarithm to be a subclass of Expr, with op and op_derivative methods, as :
import math
class Logarithm(Expr):
def op(self, x):
return math.log(x)
def op_derivative(self, var, partials):
return Multiply(
Divide(1, self.children[0]),
partials[0]
)
Now we have everything we need to take derivatives of Power expressions. For this problem, you will implement the op_derivative method for the Power class, making use of Logarithm.
* FILL IN WHERE IT STATES " #YOUR CODE HERE " *
def power_op_derivative(self, var, partials):
"""Implements derivative for Divide expressions.
Should take no more than 5 lines of code to write."""
# YOUR CODE HERE
raise NotImplementedError()
Power.op_derivative = power_op_derivative
*TEST CASES TO MAKE SURE CODE WORKS*
### Tests for `Power.op_derivative`
## We test your code by taking the derivative of expressions involving exponentiation,
## then evaluating the resulting expression for particular values of the variables
# The derivative of x**2 with respect to x is 2x, which is equal to 6 when x = 3
e = V('x') ** 2
assert_almost_equal(e.derivative('x').eval(dict(x=3)), 6)
# The derivative of x**2 with respect to y is 0
e = V('x') ** 2
assert_almost_equal(e.derivative('y').eval(dict(x=3)), 0)
### More tests for `Power.op_derivative`
e = 3 ** V('x')
assert_almost_equal(e.derivative('x').eval(dict(x=4)),
math.log(3) * (3 ** 4), places=2)
e = V('x') ** 2.8
assert_almost_equal(e.derivative('x').eval(dict(x=3)), 2.8 * 3 ** 1.8, places=2)
* CODE FOR CONEXT/BETTER UNDERSTANDING *
class Expr:
"""Abstract class representing expressions"""
def __init__(self, *args):
self.children = list(args)
self.child_values = None
def eval(self, env=None):
"""Evaluates the value of the expression with respect to a given
environment."""
# First, we evaluate the children.
# This is done here using a list comprehension,
# but we also could have written a for loop.
child_values = [c.eval(env=env) if isinstance(c, Expr) else c
for c in self.children]
# Then, we evaluate the expression itself.
if any([isinstance(v, Expr) for v in child_values]):
# Symbolic result.
return self.__class__(*child_values)
else:
# Concrete result.
return self.op(*child_values)
def op(self, *args):
"""The op method computes the value of the expression, given the
numerical value of its subexpressions. It is not implemented in
Expr, but rather, each subclass of Expr should provide its
implementation."""
raise NotImplementedError()
def __repr__(self):
"""Represents the expression as the name of the class,
followed by all the children in parentheses."""
return "%s(%s)" % (self.__class__.__name__,
', '.join(repr(c) for c in self.children))
# Expression constructors
def __add__(self, other):
return Plus(self, other)
def __radd__(self, other):
return Plus(self, other)
def __sub__(self, other):
return Minus(self, other)
def __rsub__(self, other):
return Minus(other, self)
def __mul__(self, other):
return Multiply(self, other)
def __rmul__(self, other):
return Multiply(other, self)
def __truediv__(self, other):
return Divide(self, other)
def __rtruediv__(self, other):
return Divide(other, self)
def __pow__(self, other):
return Power(self, other)
def __rpow__(self, other):
return Power(other, self)
def __neg__(self):
return Negative(self)
class V(Expr):
"""Variable."""
def __init__(self, *args):
"""Variables must be of type string."""
assert len(args) == 1
assert isinstance(args[0], str)
super().__init__(*args)
def eval(self, env=None):
"""If the variable is in the environment, returns the
value of the variable; otherwise, returns the expression."""
if env is not None and self.children[0] in env:
return env[self.children[0]]
else:
return self
class Plus(Expr):
def op(self, x, y):
return x + y
class Minus(Expr):
def op(self, x, y):
return x - y
class Multiply(Expr):
def op(self, x, y):
return x * y
class Divide(Expr):
def op(self, x, y):
return x / y
class Power(Expr):
def op(self, x, y):
return x ** y
class Negative(Expr):
def op(self, x):
return -x
def expr_derivative(self, var):
"""Computes the derivative of the expression with respect to var."""
partials = [(c.derivative(var) if isinstance(c, Expr) else 0)
for c in self.children]
return self.op_derivative(var, partials).eval()
def expr_op_derivative(self, var, partials):
raise NotImplementedError()
# Extends the existing Expr class with the newly defined methods.
Expr.derivative = expr_derivative
Expr.op_derivative = expr_op_derivative
def variable_derivative(self, var):
return 1 if self.children[0] == var else 0
# Extends the existing V class with the newly defined method.
V.derivative = variable_derivative
def plus_op_derivative(self, var, partials):
return Plus(partials[0], partials[1])
# Extends the existing Plus class...you get the idea.
Plus.op_derivative = plus_op_derivative
def negative_op_derivative(self, var, partials):
return Negative(partials[0])
Negative.op_derivative = negative_op_derivative
def multiply_op_derivative(self, var, partials):
return Plus(
Multiply(partials[0], self.children[1]),
Multiply(partials[1], self.children[0])
)
Multiply.op_derivative = multiply_op_derivative
( I a + ) = 140 Sing J = 1 ( I a + ) = 140 Sing J = 1Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started