Skip to content
Classroom

Symbolic Computation

IMathAS includes built-in functions for symbolic and numeric computation that you can use in question code. Rather than hard-coding answers, let these functions calculate values from your randomized inputs.

Basic Numeric Computation

All standard arithmetic works directly in question code:

$a = rand(2, 9)
$b = rand(1, 5)
$ans = $a * $b + sqrt($a);

Use built-in math functions for common operations:

Function Result
sqrt($x) Square root
abs($x) Absolute value
$a^$b $a^b — rewritten to safepow
round($x, $n) Round to n decimal places
floor($x), ceil($x) Round down/up
sin($x), cos($x), tan($x) Trig (radians)
log($x) Base-10 log — the interpreter rewrites log( to PHP's log10
ln($x) Natural log
nthlog($b, $x) Log base $b; there is no callable log10
exp($x) e^x
pi π ≈ 3.14159... — a constant, not a function: pi() is a syntax error

Fraction Simplification

To compute and simplify a fraction:

$num = $a * $b;
$den = $a * $c;
$gcd = gcd($num, $den);
$num_simplified = $num / $gcd;
$den_simplified = $den / $gcd;

Or use makereducedfraction($num, $den) from Format Macros to get the reduced fraction as a string (makereducedfraction(12, 18) → 2/3).

Solving Equations Numerically

For answers that require numerical solving (e.g., a root of an equation), compute the result in setup code:

// Solve: $a * x^2 + $b * x + $c = 0
$discriminant = $b**2 - 4 * $a * $c;
$root1 = (-$b + sqrt($discriminant)) / (2 * $a);
$root2 = (-$b - sqrt($discriminant)) / (2 * $a);

Then use $root1 and $root2 as the correct answers.

Working with Computed Answers

Once you have a computed answer, use it directly as the correct answer in the question:

$a = rand(2, 9)
$b = rand(1, 5) where ($b != $a)    // avoid dividing by zero
$ans = round(($a + $b) / ($a - $b), 4)

In Common Control, after that line, set $answer = $ans and $abstolerance = 0.00005 (half a unit in the fourth decimal place). If you set no tolerance, a relative tolerance of 0.0015 applies.

Displaying Computed Values in Question Text

Reference any setup variable in the question text with the $ prefix:

$pct = $rate * 100
<p>If the initial value is `$a` and the growth rate is `$pct`%, find the value after `$t` years.</p>

For computed expressions, calculate them in setup and display the result:

$r = rand(2, 9)
$area = round(pi * $r^2, 2)
<p>A circle has area `$area` square units. Find its radius.</p>

Tips

  • Always round() values before using them as correct answers when the answer should have a specific number of decimal places
  • For exact integer answers, compute with integer arithmetic and set $abstolerance = 0
  • Test your questions at boundary values of your random range to make sure no division-by-zero or undefined results occur