From WeBWorK_wiki
Revision as of 15:46, 16 January 2010 by Pearson (talk | contribs)
Jump to navigation Jump to search

Formatting Decimals: PG Code Snippet

We show how to format decimals for display in PG problems. Note that these are insertions, not a complete PG file. This code will have to be incorporated into the problem file on which you are working.

Problem Techniques Index

PG problem file Explanation



Initialization: Standard.

# both ln and log are natural log (base e)

$a = 6; # or $a = random(3,7,1);

# log base e
$b = sprintf("%0.3f", ln($a) ); # or log($a)
$solution1 = Real("$b");

$f = Formula("ln(x)"); # or log(x)
$solution2 = $f->eval(x=>$a);

# log base 10
$c = sprintf("%0.3f", ln($a)/ln(10) ); # or log($a)/log(10)
$solution3 = Real("$c");

$g = Formula("ln(x)/ln(10)"); # or log(x)/log(10)
$solution4 = $g->eval(x=>$a);

Setup: Use perl's sprintf( format, number ); command to format the decimal. The "%0.3f" portion truncates after 3 decimal places and uses zeros (not spaces) to right-justify. For answers involving money, you should set "%0.2f" for two decimal places and zero filling (for example, sprintf("%0.2f",0.5); returns 0.50). You can do a web search for more options to perl's sprintf, and also for WeBWorK's If you do further calculations with $b, be aware that numerical error may be an issue since you've reduced the number of decimal places.

We used the logarithm change of base formula log10(a) = log(a) / log(10) = ln(a) / ln(10) to get a logarithm base 10.

Note: If we load, then log and ln are both defined to be the natural logarithm (base e, not base 10). If we had loaded the older macro instead, then log would be defined as the natural logarithm (base e, not base 10), and ln would be undefined.


Notice the formatting and rounding differences 
between \( $solution1 \) and \( $solution2 \).
Try entering \( \ln($a), \log($a), 
\ln($a)/\ln(10), \log($a)/\log(10),
\mathrm{logten}($a), \mathrm{log10}($a) \).
\( \ln($a) = \) \{ ans_rule(20) \}
\( \ln($a) = \) \{ ans_rule(20) \}
\( \log_{10}($a) = \) \{ ans_rule(20) \}
\( \log_{10}($a) = \) \{ ans_rule(20) \}


Main Text: Notice the difference in decimal formatting when "Show Correct Answers" is checked and you click "Submit Answers".

ANS( $solution1->cmp() );
ANS( $solution2->cmp() );
ANS( $solution3->cmp() );
ANS( $solution4->cmp() );


Answer Evaluation: Standard.

Problem Techniques Index