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 = randint(2, 9);
$b = randint(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 |
pow($a, $b) |
$a^b |
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) |
Natural log (ln) |
log10($x) |
Base-10 log |
exp($x) |
e^x |
pi() |
π ≈ 3.14159... |
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 the fracsimp() macro from Format Macros to get a formatted fraction string.
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:
$ans = round(($a + $b) / ($a - $b), 4);
Set the answer field to $ans and tolerance to 0.0005 (half a unit in the last decimal place).
Displaying Computed Values in Question Text¶
Reference any setup variable in the question text with the $ prefix:
<p>If the initial value is `$a` and the growth rate is `$rate * 100`%, find the value after `$t` years.</p>
For computed expressions, calculate them in setup and display the result:
$display_val = round($ans, 2);
<p>Round your answer to 2 decimal places.</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 tolerance to
0 - Test your questions at boundary values of your random range to make sure no division-by-zero or undefined results occur