from notebook_preamble import J, V, define
-b +/- sqrt(b^2 - 4 * a * c)
-----------------------------
2 * a
$\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$
b neg b sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2
We use cleave to compute the sum and difference and then app2 to finish computing both roots using a quoted program [2a truediv] built with cons.
Evaluating by hand:
b neg b sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2
-b b sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2
-b b^2 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2
-b b^2 4ac - sqrt [+] [-] cleave a 2 * [truediv] cons app2
-b b^2-4ac sqrt [+] [-] cleave a 2 * [truediv] cons app2
-b sqrt(b^2-4ac) [+] [-] cleave a 2 * [truediv] cons app2
-b -b+sqrt(b^2-4ac) -b-sqrt(b^2-4ac) a 2 * [truediv] cons app2
-b -b+sqrt(b^2-4ac) -b-sqrt(b^2-4ac) 2a [truediv] cons app2
-b -b+sqrt(b^2-4ac) -b-sqrt(b^2-4ac) [2a truediv] app2
-b -b+sqrt(b^2-4ac)/2a -b-sqrt(b^2-4ac)/2a
(Eventually we’ll be able to use e.g. Sympy versions of the Joy commands to do this sort of thing symbolically. This is part of what is meant by a “categorical” language.)
-b -b+sqrt(b^2-4ac)/2a -b-sqrt(b^2-4ac)/2a roll< pop
-b+sqrt(b^2-4ac)/2a -b-sqrt(b^2-4ac)/2a -b pop
-b+sqrt(b^2-4ac)/2a -b-sqrt(b^2-4ac)/2a
b neg b sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2 roll< pop
b [neg] dupdip sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2 roll< pop
b a c [[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2 roll< pop
b a c a [[[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave] dip 2 * [truediv] cons app2 roll< pop
b a c over [[[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave] dip 2 * [truediv] cons app2 roll< pop
define('quadratic == over [[[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave] dip 2 * [truediv] cons app2 roll< pop')
J('3 1 1 quadratic')
We can define a pm plus-or-minus function:
pm == [+] [-] cleave popdd
Then quadratic becomes:
define('quadratic == over [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [truediv] cons app2')
J('3 1 1 quadratic')
pm function.¶The definition of pm above is pretty elegant, but the implementation takes a lot of steps relative to what it's accomplishing. Since we are likely to use pm more than once in the future, let's write a primitive in Python and add it to the dictionary. (This has been done already.)
def pm(stack):
a, (b, stack) = stack
p, m, = b + a, b - a
return m, (p, stack)
The resulting trace is short enough to fit on a page.
V('3 1 1 quadratic')