Introduction to MathObjects

From WeBWorK_wiki
Jump to navigation Jump to search

What are MathObjects

MathObjects are a set of formal objects introduced to make manipulation of mathematical object in WeBWorK problems more intuitive. They allow the definition of variables as common mathematical objects, e.g.,

 $f = Formula("sin(x^2+6)");
 $a = Real("sqrt(pi/6)");
 $z = Complex("1 + 5i");

These are useful (and powerful) because MathObjects "know" information about themselves: thus, we can add formulas to get new formulas, plug real objects into formulas to get formulas evaluated at those values, and calculate derivatives of formulas.

For several reasons it is usually preferable to write the MathObjects above using Compute

 $f = Compute("sin(x^2+6)");
 $a = Compute("sqrt(pi/6)");
 $z = Compute("1 + 5i");

Compute determines the kind of MathObject from the Context and from the syntax of its argument which is always a string variable.

Why use MathObjects?

MathObjects are designed to be used in two ways. First, you can use it within your perl code when writing problems as a means of making it easier to handle formulas, and in particular, to be able to use a single object to produce numeric values, TeX output and answer strings from a single formula entry. This avoids having to type a function three different ways (which makes maintaining a problem much harder). Since MathObjects also included vector and complex arthimetic, it is easier to work with these types of values as well.

More importantly using MathObjects improves the processing of student input. This is accomplished through special answer checkers that are part of the Parser package (rather than the traditional WeBWorK answer checkers). Each of these checkers has error checking customized to the type of input expected from the student and can provide helpful feedback if the syntax of the student's entry is incorrect.

Checkers are available for each of the types of values that the parser can produce (numbers, complex numbers, infinities, points, vectors, intervals, unions, formulas, lists of numbers, lists of points, lists of intervals, lists of formulas returning numbers, lists of formulas returning points, and so on). They are typically invoked using the notation $mathObject->cmp()

MathObjects are useful (and powerful) because they "know" information about themselves: thus, we can add formulas to get new formulas, plug real objects into formulas to get formulas evaluated at those values, and calculate derivatives of formulas.

Contexts

Each problem is considered in a given context. The context determines what various symbols represent. For example in "Interval" context (4,5) means the interval between 4 and 5 while in "Point" context it means a single point in the x-y plane. Among other things the context will determine which student responses will be considered "legitimate", although perhaps incorrect, and which will be considered not legitimate and will trigger a syntax error message.

  • For example in a "Vector" context <5,6,7> makes sense and the < is interpreted as an angle brackect.

In the "Numeric" context it would trigger an error.

  • In the "Inequality" context 5 < 6 the < is interpreted as a "less than" sign.
  • We've already noted that (4,5) means two different things in different contexts.


The default Context is

Context("Numeric");

and it will be sufficient to use the default context for most first semester calculus problems.

There is a list of basic contexts and links to further context information at the bottom of this document.

There are cases where one needs to use two Contexts for a single problem -- but this is not as common -- and for now we'll assume that each problem takes place in one context.


The basic contexts are straight forward and natural to use. Modifying contexts allows one to create completely new question types but it is a subtle matter to make these contexts behave as "expected".

How to create a MathObject

$a = Real(3.5);   or
$a = Compute("3.5");
$b = Complex(3, 4); or
$b = Complex("3 +4i"); or 
$b = Compute("3+4i");
$v = Vector(4,5,8);
$v = Compute("<4,5,8>");
$f = Formula("sin(x^2) + 6");

$a represents a real number 3.5 and $b (defined by either method) represents a complex number. In general using the Compute variant is preferred because the input string also serves as a model for the correct answer expected from the student.

Which MathObject types (classes) can be created?

These classes are listed and made available for writing problems in pg/macros/Value.pl. It is loaded automatically when you load MathObjects.pl.

Standard types

  • Real: Behave like real numbers
  • Infinity: The positive infinity of the extended reals. Can be negated, but can't be added to real numbers.
  • Complex: Behave like complex numbers. The interpretations of + and * are those standardly used for mathematical complex numbers.

List types

List objects are math objects whose description involves delimiters (parentheses) of some type. For example points (4, 5) or vectors <2,5> . Here are examples of the construction of the List Objects.

  • Point: $a = Point("(4,5)");
  • Vector: $b = Vector("<3,5,6!>");
  • Matrix: $c = Matrix("[[1,0],[0,1]]");
  • List: $d = List("3, 7, 3+2i");

Types that represent some subset of the real numbers

  • Interval: $I = Interval("[0,1)");
  • Set (a finite collections of points): $S = Set("{3,5,6,8}");
  • Union (of intervals and sets): $U = Union("I U J"); (I union J)

The Compute command

  • You can use the Compute command to create any of the objects above from a string
Compute("3,7,3+2i")
Compute( "[[1,0],[0,1]]" );
Compute("<cos(pi/6),sin(pi/6), pi/6>");

Why it is usually preferable to use the Compute syntax

Usually Compute is the preferred way to convert a string to a MathObject. It preserves the original string and uses it to display the correct answer expected of the student in the most useful form.

For example here are the correct answers presented to the students in the two cases: using Compute or using Vector directly.

Compute("<cos(pi/6),sin(pi/6), pi/6>")->cmp
   Correct answer presented to student:  <cos(pi/6),sin(pi/6), pi/6>
Vector("<cos(pi/6),sin(pi/6), pi/6>")->cmp
   Correct answer presented to student:  <0.866025,0.5,0.523599>

The String type

String is a special purpose type which allows comparison to an arbitrary string. The string which is the correct answer must also be one of the "legitimate" strings in the Context being used.

String("DNE")

The Formula type

A Formula object represents a function whose output is one of the MathObject types defined above. Every Formula contains a parse tree which allows you to calculate output values from given input values.

$f = Formula('2x^2+3x-5');
$n = random(2,5,1);
$g = Formula("$n * x**3") -> reduce; # double quotes necessary because of $n

How to invoke a MathObject's method

Use the standard Perl method call syntax:

$obj->method;
$obj->method($arg1,$arg2);

For example:

ANS($a->cmp);

This compares the student's answer with $a. If $a is Real then this comparison will be "fuzzy" which means that equality is checked to a tolerance defined by the current Context.

Examples of Using MathObjects

MathObjects are useful (and powerful) because they "know" information about themselves: how to add themselves to other MathObjects, take derivatives, substitute values, and to compare themselves with student answers, and even to alert students if their entries contain syntactical errors as opposed to substantiative ones.


 $f = Compute("sin(x^2+6)");
 $a = Compute("sqrt(pi/6)");
 $z = Compute("1 + 5i");
 $v = Compute("");
 $M = Compute("[1,0,1],[1,1,0],[0,1,1]");

With the definitions given above all of these operations can be performed:

 $dfdx = $f->D('x');
 $dfdx_at4 = $dfdx->eval(x=>4);
 $g = $f + $dfdx;
 $z1 = 5*$z;
 $z2 = $a + $z;
 $x = $M*$v;

The results are that $dfdx is the derivative of $f, $dfdx_at4 is f'(4), and so forth.

Use the online calculators at PGLabs to experiment with MathObjects in order to quickly learn the syntax.

Methods shared by all MathObjects

  • cmp: Returns an answer checker for the Value. All of the answer checkers are defined in the file lib/Value/AnswerChecker.pm.
  • perl: Returns a string which represents the object as Perl source code.
  • perlFunction: Returns a Perl subroutine which represents the object. (Only available for Formula objects.)
  • value: Returns the value of the object.
  • TeX: Returns a string which represents the object as a TeX math expression.
  • string: Returns a string similar to that used to create the object. May include extra parentheses.
  • stringify: Produces the output of the object when inside quotes. Depending on context this is either a TeX string or a regular string. (This is called automatically by Perl when when an object is used in string context, and should not need to be called explicitly by the problem author.)
  • getFlag("flag name"): Returns the value of one of the object's internal flags. For example: $a->getFlag("tolerance"); (see ContextFlags for a partial list )

Additional methods for Formulas

Each Formula has a parsed version of its defining string attached. This is created by the parser whose purpose is to parse a string representing a formula and turn it into a parse tree.

Additional Formula methods include:

  • eval: $f_at32 = $f->eval(x=>32) evaluates the function $f at x=32. The result is no longer a formula (the parse tree is lost) but has the type of f(32) i.e. the type of the range of $f. If $a = random(2,5,1);, then $f_at_a = $f->eval(x=>"$a"); will evaluate as expected.
  • reduce: $f = $f->reduce does some simplification of the function string --e.g. replace 1x^2 by x^2. The reduction rules are defined in the Context() and some of them are listed at List_of_parser_reduction_rules_for_MathObject_Formulas. (This is advanced information and can be skipped on the first reading.)
  • substitute: $f = $f->substitute(x=>'y') replaces all occurences of the variable x by the variable y. (One will also need to add the variable y as a legal variable to the context.) The result is a new formula. Using substitute instead of eval preserves the parse string enabling more insightful correct answer hints. (See FormattingCorrectAnswers)
  • D: $fp = $f->D('x') calculates the (partial) derivative of f with respect to x; however this will not be simplified.$fp = $f->D('x')->reduce will perform easy simplifications, but will not completely simplify the formula.


The parser which creates the parse tree Formula is defined in the file pg/lib/Parser.pm and the files in the pg/lib/Parser directory. Even though the subdirectory names under pg/lib/Parser are similar to those under pg/lib/Value they refer to different although related concepts. Under pg/lib/Parser the files refer to tokens in a string that is to be parsed, while the files under pg/lib/Value refer to MathObjects.

List of Basic Contexts

A Context is a table of values that provides defaults for the Parser and for MathObjects created while the Context is in force. As a quick example: in Numeric context the answer [math](4,5)[/math] is interpreted as a point in the two dimensional plane while in Interval context it is interpreted as the real values [math]x[/math] satisfying [math]4 \lt x \lt 5[/math].

  • Define context using: Context("Numeric");
  • To obtain the current context: $context = Context();
  • Context names: defined in pg/lib/Parser/Context/Default.pm
    • Numeric: no Matrix, Complex or Vector (or Interval) type is allowed.
    • Complex: no Matrix or Vector type is allowed. Can't use "<" to compare complex numbers.
    • Point: Nearly the same as the Vector Context below, but the angle bracket notation is not allowed and vector operations on points are not defined. This is useful if you wish to force students to perform the vector calculations before entering their answer.
    • Vector: i, j, and k are defined as unit Vectors, no Complex numbers are allowed.
    • Vector2D: i and j are defined as unit Vectors, no Complex numbers are allowed.
    • Matrix: square brackets define Matrix instead of Point or Interval
    • Interval: similar to Numeric context, but (,) and [,] create Real Intervals rather than Lists. {,} creates finite sets of Reals.
    • Full: For internal use. This context is used to seed the others.
      • pi is defined
      • i is square root of minus one, but j and k are unit Vectors
      • Matrix, Vector and Complex are all defined.
      • x is a variable

When first using MathObjects it's easiest to use the standard "Numeric" context, however as you begin to search for better ways to ask questions and to evaluate student responses you will find that customizing the context is a powerful way to proceed. There is more on this subject in the following documents.

See also