Difference between revisions of "SimplifiedSquareRoots"

From WeBWorK_wiki
Jump to navigation Jump to search
m (4 revisions: import all default namespace pages from old wiki)
(No difference)

Revision as of 15:19, 14 May 2010

Simplified Square Roots in Student Answers


This PG code shows how to require student answers to be completely reduced square roots.

Problem Techniques Index

PG problem file Explanation
DOCUMENT(); 

loadMacros(
"PGstandard.pl",
"MathObjects.pl",
"contextLimitedPowers.pl"
);

TEXT(beginproblem());

Initialization: We need to include the macros file contextLimitedPowers.pl.

###########################
#
# Subclass the numeric functions
#
package my::Function::numeric;
our @ISA = ('Parser::Function::numeric');

#
# Override sqrt() to return a special value (usually 1) when evaluated
# effectively eliminating it from the product.
#
sub sqrt {
  my $self = shift;
  my $value = $self->context->flag("setSqrt");
  return $value+1 if $value && $_[0] == 1; # force sqrt(1) to be incorrect
  return $value if $value;
  return $self->SUPER::sqrt(@_);
}

#
# end of subclass
#
package main;

###########################

Context("Numeric")->variables->are(
x => ["Real", limits => [0,2]],    # only needed if x is used in the square roots
);
#
# make sqrt() use our subclass
#
Context()->functions->set(sqrt=>{class=>'my::Function::numeric'});
Context()->flags->set(reduceConstantFunctions=>0);
#
# Don't allow fractional powers (avoids 1/2 power)
# [Could subclass exponentiation to handle that as well]
#
LimitedPowers::OnlyPositiveIntegers();

$expr = "\sqrt{12 x^2}";

$f = Compute("x*sqrt(6)");

Setup: This code is from Davide Cervone (4/25/10). See the discussion simplifying radical expressions for more information.

BEGIN_TEXT
Simplify \( $expr \) assuming that \( x \geq 0 \).
Do not enter fractional exponents.
$BR
$BR
\( $expr \) = \{ans_rule(20)\}
END_TEXT

Main Text: The problem text section of the file is as we'd expect.

$showPartialCorrectAnswers = 1;

ANS( $f-> cmp( checker => sub {
  my ($correct,$student,$ans) = @_;
  return 0 if $ans->{isPreview} || $correct != $student;
  #
  #  Get parsed formula for student and correct answers
  #
  $student = $ans->{student_formula};
  $correct = $correct->{original_formula} if defined $correct->{original_formula};
  #
  # check if equal when sqrt's are replaced by 1
  #
  Context()->flags->set(setSqrt => 1);
  delete $correct->{test_values}, $student->{test_values};
  my $OK = ($correct == $student);
  Context()->flags->set(setSqrt => 0);
  #
  Value::Error("Check to see if your answer is simplified.") unless $OK;
  return $OK;
  }, formatStudentAnswer=>"reduced"
  )
);

ENDDOCUMENT();

Answer Evaluation: Use a custom checker to check that the answers are equivalent and that they are still equivalent when sqrt() is replaced by 1 (so the stuff outside the sqrt() is equal in both).

Problem Techniques Index