Quadratic equation in J

Example for versions j602

Run calc'' in an interactive J session after loading the file. The function calc2 calculates the roots of the equation using J’s built in root function(p.).

print=: 1!:2&2
read=: 3 : '". 1!:1[1'

a=: 0&{ [ b=: 1&{ [ c=: 2&{
d=: *:@b - [:*/4,a,c
roots=: ([:-b%2*a)`(+:@a %~ (,-)@%:@d + -@b)@.([:*/*)

input=: 3 : 0
A=: read'' [ print 'A = '
B=: read'' [ print 'B = '
C=: read'' [ print 'C = '
)

calc=: 3 : 0
input''
if. A=0 do. print 'Not a quadratic equation' throw. end.
rt=: roots A,B,C
disp rt
)

disp=: 3 : 0
form=: ((('('&,)@":@{.,',',(,&')')@":@}.)@+.)`":@.(=+)
if. 1<# ~.y do.
  print 'x1 = ', form 0{y
  print 'x2 = ', form 1{y
else.
  print 'x = ', form {.y
end.
)

calc2=: 3 : 0
input''
rt=: ;}.p.|.A,B,C
disp rt
)