WeBWorK Problems

Exact values of sin and cos

Exact values of sin and cos

by Danny Glin -
Number of replies: 1
I have a few problems that involve evaluating trig functions at "nice" angles as part of a formula.  An example would be something like finding the tangent plane to the surface z=cos(x)+sin(y) at the point (pi/4,pi/4) (the coordinates of the point would be randomized).

What I'm looking for is the ability to evaluate the trig functions at these angles, and spit out an exact value answer to display as the correct answer to students.

If I do
$ans = Compute("-sin($theta1)*x + cos($theta2)*y");
then the correct answer displayed to students looks like
-sin(pi/4)*x + cos(pi/4)*y

Adding
$ans->reduce;
replaces the trig functions with decimal values.

Does anyone have a slick way to replace, for example, sin(pi/3) with sqrt(3)/2 in an algorithmic way (i.e. handle pi/6, pi/4, pi/3, etc. systematically)?  So far the only thing I've come up with is creating a hash for each of sin and cos with all of the possibilities.

Thanks,
Danny
In reply to Danny Glin

Re: Exact values of sin and cos

by Alex Jordan -
I'm not sure if this is any more slick than the hash you describe, but:

Assuming that you are only using those special multiples of pi for angles, then all of these trig values squared are rational numbers. You could take advantage of the Fraction context and do something like the following untested code:

$theta = (list_random(0, pi/6, pi/4, pi/3, pi/2) - pi)*random(-1,1,2)
#get one of the nice angles

$x = sin($theta);
Context("Fraction");

($xSqNum, $xSqDen) = Fraction(int(4*$x**2),4)->value;
#multiplication by 4 is just to make everything integer for a sec

$xNum = (sqrt($xSqNum) == int(sqrt($xSqNum)) ? sqrt($xSqNum) : "sqrt($xSqNum)";
#if numerator is 1 or 4, get 1 or 2; otherwise, get "sqrt(3)"
$xDen = sqrt($xSqDen); #will be integer 1 or 2

$x = ($x < 0) ? Formula("-(x/$xSqDen)")->reduce : Formula("x/$xSqDen")->reduce;
# to get rid of "/1" if needed
Context()->flags->set(reduceConstantFunctions=>0);
$x = $x->substitute(x => Formula($xNum));

should leave $x as a Formula object among what you would want: "1", "0", "sqrt(2)/2", "-sqrt(3)/2",...