CS111 Lab 5: Equations and Classes


Create a class to represent an equation. The equation should have only one variable (x), and will be assumed to be in the form f(x) = (expression including x). The class should have a constructor, which takes the equation as a string. It should have two methods: value(x) and plot(start, end). You can use the built-in eval() function to determine the value at any given point.

In total, you'll be defining three methods in the class:

__init__(self, equation)
This is used to create instances of the equation class. "equation" is a string, that indicates the expression to store.
value(self, x)
This calculates and returns the value of the equation for the given x value.
plot(self, start, end)
Use the turtle (or anything else) to plot the equation, from one specified x value to the other. Refer to the function plotting demo from class for how to plot functions.

Most of this lab can be pieced together from the Python 3 documentation for classes, built-in functions, turtle and the lecture examples from September 19.

Your class should be able to support programs like the following:
wave = equation("sin(x) + cos(2*x)")
print(wave.value(5))
print(wave.value(1))
wave.plot(-5, 5)
riser = equation("x * 10")
print(riser.value(6))
riser.plot(-1, 1)
print(riser.value(5) - wave.value(5))
Be sure to test your class. You can put the test code in the same file after the class, or in a different file.