Roots of a quadratic function: Difference between revisions

Content added Content deleted
m (→‎{{header|Raku}}: Make more Unicody, Update output for latest compiler release.)
(add RPL)
Line 2,355: Line 2,355:
return [x1, x2]
return [x1, x2]
</syntaxhighlight>
</syntaxhighlight>

=={{header|RPL}}==
RPL can solve quadratic functions directly :
'x^2-1E9*x+1' 'x' QUAD
returns
1: '(1000000000+s1*1000000000)/2'
which can then be turned into roots by storing 1 or -1 in the <code>s1</code> variable and evaluating the formula:
DUP 1 's1' STO EVAL SWAP -1 's1' STO EVAL
hence returning
2: 1000000000
1: 0
So let's implement the algorithm proposed by the task:
{| class="wikitable"
! RPL code
! Comment
|-
|
'''IF''' DUP TYPE 1 == '''THEN'''
'''IF''' DUP IM NOT '''THEN''' RE '''END END'''
≫ '<span style="color:blue">REALZ</span>' STO
.
≪ → a b c
≪ '''IF''' b NOT '''THEN''' c a / NEG √ DUP NEG '''ELSE'''
a c * √ b /
1 SWAP SQ 4 * - √ 2 / 0.5 +
b * NEG
DUP a / <span style="color:blue">REALZ</span>
c ROT / <span style="color:blue">REALZ</span> '''END'''
≫ ≫ '<span style="color:blue">QROOT</span>' STO
|
<span style="color:blue">REALZ</span> ''( number → number )''
if number is a complex
with no imaginary part, then turn it into a real
<span style="color:blue">QROOT</span> ''( a b c → r1 r2 ) ''
if b=0 then roots are obvious, else
q = sqrt(a*c)/b
f = 1/2+sqrt(1-4*q^2)/2
get -b*f
root1 = -b/a*f
root2 = -c/(b*f)
|}
1 -1E9 1 <span style="color:blue">QROOT</span>
actually returns a more correct answer:
2: 1000000000
1: .000000001


=={{header|Ruby}}==
=={{header|Ruby}}==