Question
I am completely stuck and would really appreciate some help. Code is done in Python, thank you! Means more thanyou think :) I've been going
I am completely stuck and would really appreciate some help. Code is done in Python, thank you! Means more thanyou think :) I've been going at it for a while now, but I am still lost.
* CODE USED FOR DERIVATIVE OF DIVIDE EXPRESSIONS*
def divide_op_derivative(self, var, partials):
return (Minus(
Multiply(partials[0], self.children[1]),
Multiply(partials[1], self.children[0])
))/(self.children[1] * self.children[1])
Minus.op_derivative = minus_op_derivative
Divide.op_derivative = divide_op_derivative
!CODE FOR CONTEXT!
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
#THANK YOU
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 fe with respect to x: lg af dg, f = f f ox ox 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 di log sa we define Logarithm to be a subclass of Expr, with op and op_derivative methods, as seen during lecture: U 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. U 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 Not ImplementedError() Power.op_derivative = power_op_derivative ### 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) 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 fe with respect to x: lg af dg, f = f f ox ox 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 di log sa we define Logarithm to be a subclass of Expr, with op and op_derivative methods, as seen during lecture: U 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. U 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 Not ImplementedError() Power.op_derivative = power_op_derivative ### 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)
Step 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