Roots of a quadratic function: Difference between revisions

m
→‎version 1: changed some variable names for easier perusing.
m (→‎version 1: change a comment to use gooder English in the REXX section header.)
m (→‎version 1: changed some variable names for easier perusing.)
Line 1,611:
The REXX language doesn't have a   '''sqrt'''   function,   nor does it have complex numbers.
<br>Since "unlimited" decimal precision is part of the language, the NUMERIC DIGITS
<br>was increased (from a default of 9) to 120 to accomodateaccommodate roots closer to zero than the other roots.
<br>Note that only 10 digits are shown in the output (precision).
<lang rexx>/*REXX program finds the roots (may be complex) of a quadratic function.*/
Line 1,617:
parse arg a b c . /*get specified arguments: A B C*/
a=a/1; b=b/1; c=c/1 /*normalize the three numbers. */
call quadratic a ,b ,c /*solve the quadratic function. */
numeric digits sqrt(digits())%1 /*reduce digits for human beans. */
r1=r1/1; r2=r2/1 /*normalize to the new digits. */
if r1j\=0 then r1=r1 || left('+',r1j>0)(r1j/1)"i" /*handle complex num.*/
r2=r2/1 /* " " " " " */
if r1jr2j\=0 then r1r2=r1r2 || left('+',r1jr2j>0)(r1jr2j/1)"i" /*handle complex num. " " " */
if r2j\=0 then r2=r2 || left( say '+ a =',r2j>0)(r2j/1)"i" a /*show the value " of A. " " */
say ' a =' a say ' b =' b /*show value of" A. " " " B. */
say ' b =' b say ' c =' c /* " " " B. " C. */
say ' c =' c say; say 'root1 =' r1 /*show 1st "root (may be " " Ccomplex). */
r2=r2/1 say 'root2 =' r2 /* " "2nd " " " " " */
say
say 'root1 =' r1 /*show 1st root (may be complex).*/
say 'root2 =' r2 /* " 2nd " " " " */
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────QUADRATIC subroutine────────────────*/
quadratic: parse arg aa ,bb,cc cc . /*obtain the specified arguments.*/
?$=sqrt(bb**2-4*aa*cc) /*compute sqrt (might be complex)*/
aa2=1 / (aa+aa) /*compute reciprocal of 2*aa */
if right(?$,1)=='i' then do /*are the roots complex? */
?in=left(?$,length(?$)-1) /*just get the # part*/
r1=-bb*aa2; r2=r1; r1j=?in*aa2; r2j=-?in*aa2
end
else do /*the roots are real (¬complex).*/
r1=(-bb+?$)*aa2; r2=(-bb-?$)*aa2; r1j=0; r2j=0
end
return
/*──────────────────────────────────SQRT subroutine─────────────────────*/
sqrt: procedure; parse arg x,f; if x=0 then return 0; d=digits(); m.=11
numeric digits 11; g i=.sqrtGleft('i',x<0); numeric do j=0 while p>9; m.j=pform; p=pd+d%4+2+1; end x=abs(x)
parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'E'_%2
do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g=.5*(g+x/g); end
do j=0 while p>9; m.j=p; p=p%2+1; end /*calculate DIGITS needed.*/
numeric digits d;return (g/1)i
.sqrtG: do ik=left('i',x<j+5 to 0); by numeric form-1; if m.=k>11; then p=d+d%4+2numeric digits m.k; xg=abs.5*(g+x/g); end
numeric digits d; return (g/1)i parse value format(x,2,1,,0) 'E0' with/* g[↑] 'E' _ .;5* return g*.5'E'_%is faster than /2 */</lang>
'''output''' when using the input of: <tt> 1 -10e5 1 </tt>
<pre>