Skip to content

Instantly share code, notes, and snippets.

@wolfsage
Last active October 12, 2015 08:07
Show Gist options
  • Save wolfsage/3996187 to your computer and use it in GitHub Desktop.
Save wolfsage/3996187 to your computer and use it in GitHub Desktop.
Quadratic Equation solver in dc (reverse polish calculator)
# Usage: dc < quadratic.dc
# Shortened to: dc -e '1 3 _4 2kscsbsa[X=]sf[lb2^4lalc**-v]sdlb_1*ldx-2la*/lfPplb_1*ldx+2la*/lfPp'
# Solves:
# x^2 + 3x – 4 = 0
1 # A
3 # B
_4 # C
# set precision
2k
# Store c, b, and a
sc
sb
sa
# For 'X=' in our output
[X=]sf
# Define our equation solver for sqrt(b^2 - 4ac) so we can -b +/- <solution> / 2a
[
lb 2 ^ # b2
4 la lc ** - # - 4ac
v # square root of the above
]sd
# Figure first X
lb _1 * ldx - # -b - sqrt(b2-4ac)
2 la */ # divided by 2a
lfP p # print 'X=<answer>'
# Figure second X
lb _1 * ldx + # -b + sqrt(b2-4ac)
2 la */ # divided by 2a
lfP p # print 'X=<answer>'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment