Quadratic equation in Factor
Word quadratic-equation takes coefficients of the equation as input and prints the solution while returning nothing. Note that this word is declared using token :: instead of : used in most cases; this means that within it lexically scoped variables can be used, in this case parameters a, b and c as well as local variables d, x0 and sd bound by :> operator. Such variables can be loaded on the stack using their names. Words and operators which process lexically scoped variables are available in dictionary locals.
Factor provides a built-in data type for complex numbers; whenever the discriminant is negative, its square root will be of type complex. In this case complex roots are printed using words real-part and imaginary-part which extract corresponding parts of a number.
readln reads a string from input stream (till the end of line), and string>number (from math.parser dictionary) converts a string to a floating-point number.
USING: formatting io kernel locals math math.functions math.parser ;
IN: quadratic-example
:: quadratic-equation ( a b c -- )
a 0 =
[ "Not a quadratic equation." printf ]
[ b sq a c * 4 * - :> d
b neg a 2 * / :> x0
d sqrt a 2 * / :> sd
d 0 =
[ x0 "x = %f\n" printf ]
[ d 0 >
[ x0 sd + x0 sd - "x1 = %f\nx2 = %f\n" printf ]
[ x0 sd + [ real-part ] [ imaginary-part ] bi "x1 = (%f, %f)\n" printf
x0 sd - [ real-part ] [ imaginary-part ] bi "x2 = (%f, %f)\n" printf ]
if
]
if
]
if ;
readln string>number
readln string>number
readln string>number
quadratic-equation
Comments
]]>blog comments powered by Disqus
]]>