WeBWorK Main Forum

Rendering output of trigonometric functions as fractions

Rendering output of trigonometric functions as fractions

by Sergio Chaves -
Number of replies: 2

I am writing a question where I want to display the values \( \sin(\theta) \) and \( \cos(\theta) \) as fractions, so students are able to identify the representative angle that they are coming from.

I am using the Fractions Context, but I do not succeed after evaluating the functions. A sample code can be found below. As you notice, I tried  several formats but I get displayed either "0.5" or " \( \sin(\pi/6) \)" for example. Is there a way to achieve this without using arrays to have the fractions stored? I want to avoid this approach as I would like to randomize the angle to either \( \pm k \frac{\pi}{6} \) or \( \pm k \frac{\pi}{4} \).

Thanks in advance!



$showPartialCorrectAnswers = 1;


$theta = list_random(Formula("0"),Formula("pi/6"), Formula("pi/4"),  Formula("pi/3"), Formula("pi/2"));

$a11 = Compute(cos($theta));
$a12 = -sin($theta);
$a21 = Formula(sin($theta));
$a22 = Formula(cos($theta));



The following matrix is the rotation matrix with angle [`\theta = [$theta] `].

[` \begin{bmatrix}
[$a11] & [$a12] \\
[$a21] & [$a22]



In reply to Sergio Chaves

Re: Rendering output of trigonometric functions as fractions

by Alex Jordan -

I have an algorithmic routine for handling this. It's half baked into a macro library and I just need time to clean it and test it before contributing it.

If you *know* you have a number that is output from sine or cosine applied to a nice angle (multiple of pi,pi/2,pi/3,pi/4,pi/6) then you know that squaring that number gives you a rational number.

For example, if $y = cos(pi/6), then $y**2 is 3/4.  It might be a floating point real that is only close to 3/4, but that is OK with what comes next.

The Fraction context will turn $y**2 into a clean Fraction. So $y2 = Fraction($y**2) is now the Fraction object 3/4.

And now
makes $n the numerator and $d the denominator.

If $n==0, return Real(0).

Else if $d==1, that implies $n must be 1. Now return Real(1) (see *).

Else $d must be 4, and $n is among 1,2,3. If $n==1, return Fraction(1,2) (see *). 

Else $n==2 or $n==3. Return Formula("sqrt($n)/2"), with context flag reduceConstantFunctions=>0 (see *).

*Always modify the output according to the sign of the original $y.

Now this much could just as easily be put into a hash that you keep in a macro library, instead of being algorithmic. But what I really have handles general rational multiples of nice trig values as well. It's just a little more complicated.

In reply to Alex Jordan

Re: Rendering output of trigonometric functions as fractions

by Sergio Chaves -

Thank you Alex for your suggestion! I was able to implement it into my code.