Roots of a quadratic function: Difference between revisions
Content added Content deleted
m (→{{header|K}}: Add comment) |
(Added XPL0 example.) |
||
Line 2,779: | Line 2,779: | ||
coefficients: 1, -1000, 1 -> two real roots: 999.998999999 and 0.001000001000002 |
coefficients: 1, -1000, 1 -> two real roots: 999.998999999 and 0.001000001000002 |
||
coefficients: 1, -1000000000, 1 -> two real roots: 1000000000 and 1e-09 |
coefficients: 1, -1000000000, 1 -> two real roots: 1000000000 and 1e-09 |
||
</pre> |
|||
=={{header|XPL0}}== |
|||
{{trans|Go}} |
|||
<syntaxhighlight lang "XPL0">include xpllib; \for Print |
|||
func real QuadRoots(A, B, C); \Return roots of quadratic equation |
|||
real A, B, C; |
|||
real D, E, R; |
|||
[R:= [0., 0., 0.]; |
|||
R(0):= 0.; R(1):= 0.; R(2):= 0.; |
|||
D:= B*B - 4.*A*C; |
|||
case of |
|||
D = 0.: [R(0):= -B / (2.*A); \single root |
|||
R(1):= R(0); |
|||
]; |
|||
D > 0.: [if B < 0. then \two real roots |
|||
E:= sqrt(D) - B |
|||
else E:= -sqrt(D) - B; |
|||
R(0):= E / (2.*A); |
|||
R(1):= 2. * C / E; |
|||
]; |
|||
D < 0.: [R(0):= -B / (2.*A); \real |
|||
R(2):= sqrt(-D) /(2.*A); \imaginary |
|||
] |
|||
other []; \D overflowed or a coefficient was NaN |
|||
return R; |
|||
]; |
|||
func Test(A, B, C); |
|||
real A, B, C; |
|||
real R; |
|||
[Print("coefficients: %g, %g, %g -> ", A, B, C); |
|||
R:= QuadRoots(A, B, C); |
|||
if R(2) # 0. then |
|||
Print("two complex roots: %g+%gi, %g-%gi\n", R(0), R(2), R(0), R(2)) |
|||
else [if R(0) = R(1) then |
|||
Print("one real root: %g\n", R(0)) |
|||
else Print("two real roots: %15.15g, %15.15g\n", R(0), R(1)); |
|||
]; |
|||
]; |
|||
real C; int I; |
|||
[C:= [ [1., -2., 1.], |
|||
[1., 0., 1.], |
|||
[1., -10., 1.], |
|||
[1., -1000., 1.], |
|||
[1., -1e9, 1.], |
|||
[1., -4., 6.] ]; |
|||
for I:= 0 to 5 do |
|||
Test(C(I,0), C(I,1), C(I,2)); |
|||
]</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
coefficients: 1, -2, 1 -> one real root: 1 |
|||
coefficients: 1, 0, 1 -> two complex roots: 0+1i, 0-1i |
|||
coefficients: 1, -10, 1 -> two real roots: 9.89897948556636, 0.101020514433644 |
|||
coefficients: 1, -1000, 1 -> two real roots: 999.998999999, 0.001000001000002 |
|||
coefficients: 1, -1e9, 1 -> two real roots: 1000000000, 0.000000001 |
|||
coefficients: 1, -4, 6 -> two complex roots: 2+1.41421i, 2-1.41421i |
|||
</pre> |
</pre> |
||