Roots of a quadratic function: Difference between revisions
m
→{{header|Wren}}: Minor tidy
m (→{{header|Modula-3}}: was wrong) |
m (→{{header|Wren}}: Minor tidy) |
||
(21 intermediate revisions by 15 users not shown) | |||
Line 7:
(For double-precision floats, set <math>b = -10^9</math>.)
Consider the following implementation in [[Ada]]:
<
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
Line 22:
begin
Put_Line ("X1 =" & Float'Image (R (1)) & " X2 =" & Float'Image (R (2)));
end Quadratic_Equation;</
{{out}}
<pre>X1 = 1.00000E+06 X2 = 0.00000E+00</pre>
Line 34:
'''Task''': do it better. This means that given <math>a = 1</math>, <math>b = -10^9</math>, and <math>c = 1</math>, both of the roots your program returns should be greater than <math>10^{-11}</math>. Or, if your language can't do floating-point arithmetic any more precisely than single precision, your program should be able to handle <math>b = -10^6</math>. Either way, show what your program gives as the roots of the quadratic in question. See page 9 of
[https://www.validlab.com/goldberg/paper.pdf "What Every Scientist Should Know About Floating-Point Arithmetic"] for a possible algorithm.
=={{header|11l}}==
<syntaxhighlight lang="11l">F quad_roots(a, b, c)
V sqd = Complex(b^2 - 4*a*c) ^ 0.5
R ((-b + sqd) / (2 * a),
(-b - sqd) / (2 * a))
V testcases = [(3.0, 4.0, 4 / 3),
(3.0, 2.0, -1.0),
(3.0, 2.0, 1.0),
(1.0, -1e9, 1.0),
(1.0, -1e100, 1.0)]
L(a, b, c) testcases
V (r1, r2) = quad_roots(a, b, c)
print(r1, end' ‘ ’)
print(r2)</syntaxhighlight>
{{out}}
<pre>
-0.666667+0i -0.666667+0i
0.333333+0i -1+0i
-0.333333+0.471405i -0.333333-0.471405i
1e+09+0i 0i
1e+100+0i 0i
</pre>
=={{header|Ada}}==
<
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
Line 57 ⟶ 83:
begin
Put_Line ("X1 =" & Float'Image (R (1)) & " X2 =" & Float'Image (R (2)));
end Quadratic_Equation;</
Here precision loss is prevented by checking signs of operands. On errors, Constraint_Error is propagated on numeric errors and when roots are complex.
{{out}}
Line 71 ⟶ 97:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - probably need to "USE" the compl ENVIRON}}
<
BEGIN
Line 125 ⟶ 151:
ESAC
OD
END # quadratic_equation #</
{{out}}
<pre>
Line 149 ⟶ 175:
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?p=276617#276617 discussion]
<
MsgBox % quadratic(u,v, 1,3,2) ", " u ", " v
MsgBox % quadratic(u,v, -2,4,-2) ", " u ", " v
Line 171 ⟶ 197:
x2 := c/a/x1
Return 2
}</
=={{header|BBC BASIC}}==
<
READ a$, b$, c$
PRINT "For a = " ; a$ ", b = " ; b$ ", c = " ; c$ TAB(32) ;
Line 201 ⟶ 227:
PRINT "the complex roots are " ; -b/2/a " +/- " ; SQR(-d)/2/a "*i"
ENDCASE
ENDPROC</
{{out}}
<pre>For a = 1, b = -1E9, c = 1 the real roots are 1E9 and 1E-9
Line 213 ⟶ 239:
=={{header|C}}==
Code that tries to avoid floating point overflow and other unfortunate loss of precissions: (compiled with <code>gcc -std=c99</code> for <code>complex</code>, though easily adapted to just real numbers)
<
#include <stdlib.h>
#include <complex.h>
Line 273 ⟶ 299:
return 0;
}</
{{out}}<pre>(-1e+12 + 0 i), (-1 + 0 i)
(1.00208e+07 + 0 i), (9.9792e-08 + 0 i)</pre>
<
#include <math.h>
#include <complex.h>
Line 288 ⟶ 314:
x[0] = (-b + csqrt(delta)) / (2.0*a);
x[1] = (-b - csqrt(delta)) / (2.0*a);
}</
{{trans|C++}}
<
{
b /= a;
Line 304 ⟶ 330:
x[1] = c/sol;
}
}</
<
{
complex double x[2];
Line 320 ⟶ 346:
return 0;
}</
<pre>x1 = (1.00000000000000000000e+20, 0.00000000000000000000e+00)
Line 329 ⟶ 355:
=={{header|C sharp|C#}}==
<
using System.Numerics;
Line 344 ⟶ 370:
Console.WriteLine(Solve(1, -1E20, 1));
}
}</
{{out}}
<pre>((1E+20, 0), (1E-20, 0))</pre>
=={{header|C++}}==
<
#include <utility>
#include <complex>
Line 376 ⟶ 402:
std::pair<complex, complex> result = solve_quadratic_equation(1, -1e20, 1);
std::cout << result.first << ", " << result.second << std::endl;
}</
{{out}}
(1e+20,0), (1e-20,0)
Line 382 ⟶ 408:
=={{header|Clojure}}==
<
"Compute the roots of a quadratic in the form ax^2 + bx + c = 1.
Returns any of nil, a float, or a vector."
Line 392 ⟶ 418:
(zero? sq-d) (f +)
(pos? sq-d) [(f +) (f -)]
:else nil))) ; maybe our number ended up as NaN</
{{out}}
<
nil
user=> (quadratic 1.0 2.0 1.0)
Line 401 ⟶ 427:
user=> (quadratic 1.0 3.0 1.0)
[2.618033988749895 0.3819660112501051]
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(list
(/ (+ (- b) (sqrt (- (expt b 2) (* 4 a c)))) (* 2 a))
(/ (- (- b) (sqrt (- (expt b 2) (* 4 a c)))) (* 2 a))))</
=={{header|D}}==
<
CommonType!(T1, T2, T3)[] naiveQR(T1, T2, T3)
Line 456 ⟶ 482:
writefln(" Naive: [%(%g, %)]", naiveQR(1.0L, -10e5L, 1.0L));
writefln("Cautious: [%(%g, %)]", cautiQR(1.0L, -10e5L, 1.0L));
}</
{{out}}
<pre>With 32 bit float type:
Line 469 ⟶ 495:
Naive: [1e+06, 1e-06]
Cautious: [1e+06, 1e-06]</pre>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Roots_of_a_quadratic_function#Pascal Pascal].
=={{header|Elixir}}==
<
def roots(a, b, c) do
IO.puts "Roots of a quadratic function (#{a}, #{b}, #{c})"
Line 494 ⟶ 523:
Quadratic.roots(1, -1.0e10, 1)
Quadratic.roots(1, 2, 3)
Quadratic.roots(2, -1, -6)</
{{out}}
Line 513 ⟶ 542:
=={{header|ERRE}}==
<syntaxhighlight lang="text">PROGRAM QUADRATIC
PROCEDURE SOLVE_QUADRATIC
Line 546 ⟶ 575:
DATA(1,3,2)
DATA(3,4,5)
END PROGRAM</
{{out}}
<pre>For a= 1 ,b=-1E+09 ,c= 1 the real roots are 1E+09 and 1E-09
Line 559 ⟶ 588:
=={{header|Factor}}==
{{trans|Ada}}
<
b sq a c * 4 * - sqrt :> sd
b 0 <
[ b neg sd + a 2 * / ]
[ b neg sd - a 2 * / ] if :> x
x c a x * / ;</
<
--- Data stack:
1.0e+20
9.999999999999999e-21</
Middlebrook method
<
a c * sqrt b / :> q
1 4 q sq * - sqrt 0.5 * 0.5 + :> f
b neg a / f * c neg b / f / ;
</syntaxhighlight>
<
--- Data stack:
1.0e+20
1.0e-20</
=={{header|Forth}}==
Without locals:
<
frot frot
( c a b )
Line 598 ⟶ 627:
2e f/ fover f/
( c a r1 )
frot frot f/ fover f/ ;</
With locals:
<
b b f* 4e a f* c f* f-
fdup f0< if abort" imaginary roots" then
Line 609 ⟶ 638:
\ test
1 set-precision
1e -1e6 1e quadratic fs. fs. \ 1e-6 1e6</
=={{header|Fortran}}==
===Fortran 90===
{{works with|Fortran|90 and later}}
<
IMPLICIT NONE
Line 647 ⟶ 676:
WRITE(*,*) "The roots are complex:"
WRITE(*,"(2(A,2E23.15,A))") "Root1 = ", croot1, "j ", " Root2 = ", croot2, "j"
END IF</
{{out}}
Coefficients are: a = 0.300000000000000E+01 b = 0.400000000000000E+01 c = 0.133333333330000E+01
Line 667 ⟶ 696:
===Fortran I===
Source code written in FORTRAN I (october 1956) for the IBM 704.
<
COMPUTE ROOTS OF A QUADRATIC FUNCTION - 1956
READ 100,A,B,C
Line 695 ⟶ 724:
332 FORMAT(3HX1=,E12.5,4H,X2=,E12.5)
999 STOP
</syntaxhighlight>
=={{header|FreeBASIC}}==
{{libheader|GMP}}
<syntaxhighlight lang="freebasic">' version 20-12-2020
' compile with: fbc -s console
#Include Once "gmp.bi"
Sub solvequadratic_n(a As Double ,b As Double, c As Double)
Dim As Double f, d = b ^ 2 - 4 * a * c
Select Case Sgn(d)
Case 0
Print "1: the single root is "; -b / 2 / a
Case 1
Print "1: the real roots are "; (-b + Sqr(d)) / 2 * a; " and ";(-b - Sqr(d)) / 2 * a
Case -1
Print "1: the complex roots are "; -b / 2 / a; " +/- "; Sqr(-d) / 2 / a; "*i"
End Select
End Sub
Sub solvequadratic_c(a As Double ,b As Double, c As Double)
Dim As Double f, d = b ^ 2 - 4 * a * c
Select Case Sgn(d)
Case 0
Print "2: the single root is "; -b / 2 / a
Case 1
f = (1 + Sqr(1 - 4 * a *c / b ^ 2)) / 2
Print "2: the real roots are "; -f * b / a; " and "; -c / b / f
Case -1
Print "2: the complex roots are "; -b / 2 / a; " +/- "; Sqr(-d) / 2 / a; "*i"
End Select
End Sub
Sub solvequadratic_gmp(a_ As Double ,b_ As Double, c_ As Double)
#Define PRECISION 1024 ' about 300 digits
#Define MAX 25
Dim As ZString Ptr text
text = Callocate (1000)
Mpf_set_default_prec(PRECISION)
Dim As Mpf_ptr a, b, c, d, t
a = Allocate(Len(__mpf_struct)) : Mpf_init_set_d(a, a_)
b = Allocate(Len(__mpf_struct)) : Mpf_init_set_d(b, b_)
c = Allocate(Len(__mpf_struct)) : Mpf_init_set_d(c, c_)
d = Allocate(Len(__mpf_struct)) : Mpf_init(d)
t = Allocate(Len(__mpf_struct)) : Mpf_init(t)
mpf_mul(d, b, b)
mpf_set_ui(t, 4)
mpf_mul(t, t, a)
mpf_mul(t, t, c)
mpf_sub(d, d, t)
Select Case mpf_sgn(d)
Case 0
mpf_neg(t, b)
mpf_div_ui(t, t, 2)
mpf_div(t, t, a)
Gmp_sprintf(text,"%.*Fe", MAX, t)
Print "3: the single root is "; *text
Case Is > 0
mpf_sqrt(d, d)
mpf_add(a, a, a)
mpf_neg(t, b)
mpf_add(t, t, d)
mpf_div(t, t, a)
Gmp_sprintf(text,"%.*Fe", MAX, t)
Print "3: the real roots are "; *text; " and ";
mpf_neg(t, b)
mpf_sub(t, t, d)
mpf_div(t, t, a)
Gmp_sprintf(text,"%.*Fe", MAX, t)
Print *text
Case Is < 0
mpf_neg(t, b)
mpf_div_ui(t, t, 2)
mpf_div(t, t, a)
Gmp_sprintf(text,"%.*Fe", MAX, t)
Print "3: the complex roots are "; *text; " +/- ";
mpf_neg(t, d)
mpf_sqrt(t, t)
mpf_div_ui(t, t, 2)
mpf_div(t, t, a)
Gmp_sprintf(text,"%.*Fe", MAX, t)
Print *text; "*i"
End Select
End Sub
' ------=< MAIN >=------
Dim As Double a, b, c
Print "1: is the naieve way"
Print "2: is the cautious way"
Print "3: is the naieve way with help of GMP"
Print
For i As Integer = 1 To 10
Read a, b, c
Print "Find root(s) for "; Str(a); "X^2"; IIf(b < 0, "", "+");
Print Str(b); "X"; IIf(c < 0, "", "+"); Str(c)
solvequadratic_n(a, b , c)
solvequadratic_c(a, b , c)
solvequadratic_gmp(a, b , c)
Print
Next
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
Data 1, -1E9, 1
Data 1, 0, 1
Data 2, -1, -6
Data 1, 2, -2
Data 0.5, 1.4142135623731, 1
Data 1, 3, 2
Data 3, 4, 5
Data 1, -1e100, 1
Data 1, -1e200, 1
Data 1, -1e300, 1</syntaxhighlight>
{{out}}
<pre>1: is the naieve way
2: is the cautious way
3: is the naieve way with help of GMP
Find root(s) for 1X^2-1000000000X+1
1: the real roots are 1000000000 and 0
2: the real roots are 1000000000 and 1e-009
3: the real roots are 9.9999999999999999900000000e+08 and 1.0000000000000000010000000e-09
Find root(s) for 1X^2+0X+1
1: the complex roots are -0 +/- 1*i
2: the complex roots are -0 +/- 1*i
3: the complex roots are 0.0000000000000000000000000e+00 +/- 1.0000000000000000000000000e+00*i
Find root(s) for 2X^2-1X-6
1: the real roots are 8 and -6
2: the real roots are 2 and -1.5
3: the real roots are 2.0000000000000000000000000e+00 and -1.5000000000000000000000000e+00
Find root(s) for 1X^2+2X-2
1: the real roots are 0.7320508075688772 and -2.732050807568877
2: the real roots are -2.732050807568877 and 0.7320508075688773
3: the real roots are 7.3205080756887729352744634e-01 and -2.7320508075688772935274463e+00
Find root(s) for 0.5X^2+1.4142135623731X+1
1: the real roots are -0.3535533607909526 and -0.3535534203955974
2: the real roots are -1.414213681582389 and -1.414213443163811
3: the real roots are -1.4142134436707580875788206e+00 and -1.4142136810754419733330398e+00
Find root(s) for 1X^2+3X+2
1: the real roots are -1 and -2
2: the real roots are -2 and -0.9999999999999999
3: the real roots are -1.0000000000000000000000000e+00 and -2.0000000000000000000000000e+00
Find root(s) for 3X^2+4X+5
1: the complex roots are -0.6666666666666666 +/- 1.105541596785133*i
2: the complex roots are -0.6666666666666666 +/- 1.105541596785133*i
3: the complex roots are -6.6666666666666666666666667e-01 +/- 1.1055415967851332830383109e+00*i
Find root(s) for 1X^2-1e+100X+1
1: the real roots are 1e+100 and 0
2: the real roots are 1e+100 and 1e-100
3: the real roots are 1.0000000000000000159028911e+100 and 9.9999999999999998409710889e-101
Find root(s) for 1X^2-1e+200X+1
1: the real roots are 1.#INF and -1.#INF
2: the real roots are 1e+200 and 1e-200
3: the real roots are 9.9999999999999996973312221e+199 and 0.0000000000000000000000000e+00
Find root(s) for 1X^2-1e+300X+1
1: the real roots are 1.#INF and -1.#INF
2: the real roots are 1e+300 and 1e-300
3: the real roots are 1.0000000000000000525047603e+300 and 0.0000000000000000000000000e+00</pre>
=={{header|GAP}}==
<
local d;
d := Sqrt(b*b - 4*a*c);
Line 711 ⟶ 923:
# This works also with floating-point numbers
QuadraticRoots(2.0, 2.0, -1.0);
# [ 0.366025, -1.36603 ]</
=={{header|Go}}==
<
import (
Line 770 ⟶ 982:
test(c[0], c[1], c[2])
}
}</
{{out}}
<pre>
Line 781 ⟶ 993:
=={{header|Haskell}}==
<
type CD = Complex Double
quadraticRoots :: (CD, CD, CD) -> (CD, CD)
quadraticRoots (a, b, c)
)
| otherwise =
( (- b + d) / (2 * a),
(2 * c) / (- b + d)
)
where
d = sqrt $ b ^ 2 - 4 * a * c
Line 797 ⟶ 1,014:
mapM_
(print . quadraticRoots)
[ (3, 4, 4 / 3),
(3, 2, -1),
(3, 2, 1),
(1, -10e5, 1),
(1, -10e9, 1)
]</syntaxhighlight>
{{Out}}
<pre>((-0.6666666666666666) :+ 0.0,(-0.6666666666666666) :+ 0.0)
Line 810 ⟶ 1,032:
Works in both languages.
<
solve(1.0, -10.0e5, 1.0)
end
Line 819 ⟶ 1,041:
else [r1 := (-b-d)/(2.0*a), c/(a*r1)]
write(a,"*x^2 + ",b,"*x + ",c," has roots ",roots[1]," and ",roots[2])
end</
{{out}}
Line 829 ⟶ 1,051:
=={{header|IDL}}==
<
print, "input a, press enter, input b, press enter, input c, press enter"
Line 845 ⟶ 1,067:
e= y/z
print, d,e</
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">
100 PROGRAM "Quadratic.bas"
110 PRINT "Enter coefficients a, b and c:":INPUT PROMPT "a= ,b= ,c= ":A,B,C
Line 863 ⟶ 1,085:
220 PRINT "The complex roots are ";-B/2/A;"+/- ";STR$(SQR(-D)/2/A);"*i"
230 END SELECT
240 END IF</
=={{header|J}}==
'''Solution''' use J's built-in polynomial solver:
p.
This primitive converts between the coefficient form of a polynomial (with the exponents being the array indices of the coefficients) and the multiplier-and-roots for of a polynomial (with two boxes, the first containing the multiplier and the second containing the roots).
'''Example''' using inputs from other solutions and the unstable example from the task description:
<
> {:"1 p. coeff
_0.666667 _0.666667
Line 876 ⟶ 1,101:
_0.333333j0.471405 _0.333333j_0.471405
1e6 1e_6
1e9 1e_9</
Of course <code>p.</code> generalizes to polynomials of arbitrary order (which isn't as great as that might sound, because of practical limitations). Given the coefficients <code>p.</code> returns the multiplier and roots of the polynomial. Given the multiplier and roots it returns the coefficients. For example using the cubic <math>0 + 16x - 12x^2 + 2x^3</math>:
<
+-+-----+
|2|4 2 0|
+-+-----+
p. 2 ; 4 2 0 NB. return coefficients
0 16 _12 2</
Exploring the limits of precision:
<
100000 1e_5
1 _1e5 1 p. 1{::p. 1 _1e5 1 NB. test roots
Line 897 ⟶ 1,122:
1e_5 _1e_15
1 _1e5 1 p. 1e5 1e_5-1e_5 _1e_15 NB. test displayed roots with adjustment
_3.38436e_7 0</
When these "roots" are plugged back into the original polynomial, the results are nowhere near zero. However, double precision floating point does not have enough bits to represent the (extremely close) answers that would give a zero result.
Line 903 ⟶ 1,128:
Middlebrook formula implemented in J
<
'a b c' =. y
q=. b %~ %: a * c
Line 911 ⟶ 1,136:
q_r 1 _1e6 1
1e6 1e_6</
=={{header|Java}}==
<
private static class Complex {
double re, im;
Line 987 ⟶ 1,212:
}
}
}</
{{out}}
<pre>
Line 1,025 ⟶ 1,250:
'''Section 1''': Complex numbers (scrolling window)
<div style="overflow:scroll; height:200px;">
<
def real(z): if (z|type) == "number" then z else z[0] end;
Line 1,090 ⟶ 1,315:
| [ ($r * cos), ($r * sin)]
end
end ;</
'''Section 2:''' quadratic_roots(a;b;c)
<
# if none, emit empty;
# otherwise always emit two.
Line 1,108 ⟶ 1,333:
negate(divide(c; multiply(b; $f)))
end
;</
'''Section 3''':
Produce a table showing [i, error, solution] for solutions to x^2 - 10^i + 1 = 0
<
def pow(i): . as $in | reduce range(0;i) as $i (1; . * $in);
def poly(a;b;c): plus( plus( multiply(a; multiply(.;.)); multiply(b;.)); c);
Line 1,129 ⟶ 1,354:
;
example</
{{Out}} (scrolling window)
<div style="overflow:scroll; height:200px;">
<syntaxhighlight lang="sh">
$ jq -M -r -n -f Roots_of_a_quadratic_function.jq
0: error = +0 x=[0.5,0.8660254037844386]
Line 1,159 ⟶ 1,384:
11: error = +0 x=[1e-11,-0]
12: error = 1 x=[1000000000000,0]
12: error = +0 x=[1e-12,-0]</
=={{header|Julia}}==
Line 1,166 ⟶ 1,391:
Alternative solutions might make use of Julia's Polynomials or Roots packages.
<
function quadroots(x::Real, y::Real, z::Real)
Line 1,190 ⟶ 1,415:
for (x, y, z) in zip(a, b, c)
@printf "The roots of %.2fx² + %.2fx + %.2f\n\tx₀ = (%s)\n" x y z join(round.(quadroots(x, y, z), 2), ", ")
end</
{{out}}
Line 1,201 ⟶ 1,426:
The roots of 10.00x² + 1.00x + 1.00
x₀ = (-0.05 + 0.31im, -0.05 - 0.31im)</pre>
=={{header|K}}==
===K6===
{{works with|ngn/k}}
<syntaxhighlight lang="k"> / naive method
/ sqr[x] and sqrt[x] must be provided
quf:{[a;b;c]; s:sqrt[sqr[b]-4*a*c];(-b+s;-b-s)%2*a}
quf[0.5;-2.5;2]
1.0 4.0
quf[1;8;15]
-5.0 -3.0
quf[1;10;1]
-9.898979485566356 -0.10102051443364424
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|Java}}
<
data class Equation(val a: Double, val b: Double, val c: Double) {
Line 1,247 ⟶ 1,487:
equations.forEach { println("$it\n" + it.quadraticRoots) }
}</
{{out}}
<pre>Equation(a=1.0, b=22.0, c=-1323.0)
Line 1,263 ⟶ 1,503:
=={{header|lambdatalk}}==
<
1) using lambdas:
Line 1,325 ⟶ 1,565:
x1 = 1
x2 = 1
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<
'assume a<>0
print quad$(a,b,c)
Line 1,341 ⟶ 1,581:
quad$=str$(x/(2*a)+sqr(D)/(2*a));" , ";str$(x/(2*a)-sqr(D)/(2*a))
end if
end function</
=={{header|Logo}}==
<
localmake "d sqrt (:b*:b - 4*:a*:c)
if :b < 0 [make "d minus :d]
output list (:d-:b)/(2*:a) (2*:c)/(:d-:b)
end</
=={{header|Lua}}==
Line 1,354 ⟶ 1,594:
like that from the Complex Numbers article. However, this should be enough to demonstrate its accuracy:
<
if b < 0 then return qsolve(-a, -b, -c) end
val = b + (b^2 - 4*a*c)^(1/2) --this never exhibits instability if b > 0
Line 1,362 ⟶ 1,602:
for i = 1, 12 do
print(qsolve(1, 0-10^i, 1))
end</
The "trick" lies in avoiding subtracting large values that differ by a small amount, which is the source of instability in the "normal" formula. It is trivial to prove that 2c/(b + sqrt(b^2-4ac)) = (b - sqrt(b^2-4ac))/2a.
=={{header|Maple}}==
<
solve(1.0*x^2-10.0^9*x+1.0,x,explicit,allsolutions);
fsolve(x^2-10^9*x+1,x,complex);</
{{out}}
<pre> (1/2) (1/2)
Line 1,384 ⟶ 1,624:
1.000000000 10 , 1.000000000 10 </pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Possible ways to do this are (symbolic and numeric examples):
<
Solve[x^2 - 10^5 x + 1 == 0, x]
Root[#1^2 - 10^5 #1 + 1 &, 1]
Line 1,394 ⟶ 1,634:
FindInstance[x^2 - 10^5 x + 1 == 0, x, Reals, 2]
FindRoot[x^2 - 10^5 x + 1 == 0, {x, 0}]
FindRoot[x^2 - 10^5 x + 1 == 0, {x, 10^6}]</
gives back:
Line 1,434 ⟶ 1,674:
=={{header|MATLAB}} / {{header|Octave}}==
<
=={{header|Maxima}}==
<
/* 2 2
Line 1,452 ⟶ 1,692:
bfloat(%);
/* [x = 1.0000000000000000009999920675269450501b-9,
x = 9.99999999999999998999999999999999999b8] */</
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П2 С/П /-/ <-> / 2 / П3 x^2 С/П
ИП2 / - Вx <-> КвКор НОП x>=0 28 ИП3
x<0 24 <-> /-/ + / Вx С/П /-/ КвКор
ИП3 С/П</
''Input:'' a С/П b С/П c С/П
Line 1,466 ⟶ 1,706:
=={{header|Modula-3}}==
{{trans|Ada}}
<
IMPORT IO, Fmt, Math;
Line 1,490 ⟶ 1,730:
r := Solve(1.0D0, -10.0D5, 1.0D0);
IO.Put("X1 = " & Fmt.LongReal(r[1]) & " X2 = " & Fmt.LongReal(r[2]) & "\n");
END Quad.</
=={{header|Nim}}==
<syntaxhighlight lang="nim">import math, complex, strformat
const Epsilon = 1e-15
type
SolKind = enum solDouble, solFloat, solComplex
Roots = object
case kind: SolKind
of solDouble:
fvalue: float
of solFloat:
fvalues: (float, float)
of solComplex:
cvalues: (Complex64, Complex64)
func quadRoots(a, b, c: float): Roots =
if a == 0:
raise newException(ValueError, "first coefficient cannot be null.")
let den = a * 2
let Δ = b * b - a * c * 4
if abs(Δ) < Epsilon:
result = Roots(kind: solDouble, fvalue: -b / den)
elif Δ < 0:
let r = -b / den
let i = sqrt(-Δ) / den
result = Roots(kind: solComplex, cvalues: (complex64(r, i), complex64(r, -i)))
else:
let r = (if b < 0: -b + sqrt(Δ) else: -b - sqrt(Δ)) / den
result = Roots(kind: solFloat, fvalues: (r, c / (a * r)))
func `$`(r: Roots): string =
case r.kind
of solDouble:
result = $r.fvalue
of solFloat:
result = &"{r.fvalues[0]}, {r.fvalues[1]}"
of solComplex:
result = &"{r.cvalues[0].re} + {r.cvalues[0].im}i, {r.cvalues[1].re} + {r.cvalues[1].im}i"
when isMainModule:
const Equations = [(1.0, -2.0, 1.0),
(10.0, 1.0, 1.0),
(1.0, -10.0, 1.0),
(1.0, -1000.0, 1.0),
(1.0, -1e9, 1.0)]
for (a, b, c) in Equations:
echo &"Equation: {a=}, {b=}, {c=}"
let roots = quadRoots(a, b, c)
let plural = if roots.kind == solDouble: "" else: "s"
echo &" root{plural}: {roots}"</syntaxhighlight>
{{out}}
<pre>Equation: a=1.0, b=-2.0, c=1.0
root: 1.0
Equation: a=10.0, b=1.0, c=1.0
roots: -0.05 + 0.3122498999199199i, -0.05 + -0.3122498999199199i
Equation: a=1.0, b=-10.0, c=1.0
roots: 9.898979485566356, 0.1010205144336438
Equation: a=1.0, b=-1000.0, c=1.0
roots: 999.998999999, 0.001000001000002
Equation: a=1.0, b=-1000000000.0, c=1.0
roots: 1000000000.0, 1e-09</pre>
=={{header|OCaml}}==
<
| RealRoots of float * float
| ComplexRoots of Complex.t * Complex.t ;;
Line 1,513 ⟶ 1,824:
in
RealRoots (r, c /. (r *. a))
;;</
{{out}}
<
- : quadroots = RealRoots (-1.4142135623730951, 1.4142135623730949)
Line 1,525 ⟶ 1,836:
# quadsolve 1.0 (-1.0e5) 1.0 ;;
- : quadroots = RealRoots (99999.99999, 1.0000000001000001e-005)</
=={{header|Octave}}==
Line 1,532 ⟶ 1,843:
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.8.0+}}
<
{{trans|C}}
Otherwise, coding directly:
<
b /= a;
c /= a;
Line 1,546 ⟶ 1,857:
[sol,c/sol]
)
};</
Either way,
<syntaxhighlight lang
gives one root around 0.000000001000000000000000001 and one root around 999999999.999999999.
=={{header|Pascal}}==
some parts translated from Modula2
<
var
Line 1,582 ⟶ 1,893:
end;
end.
</syntaxhighlight>
{{out}}
<pre>
Line 1,593 ⟶ 1,904:
=={{header|Perl}}==
When using [http://perldoc.perl.org/Math/Complex.html Math::Complex] perl automatically convert numbers when necessary.
<
($x1,$x2) = solveQuad(1,2,3);
Line 1,604 ⟶ 1,915:
my $root = sqrt($b**2 - 4*$a*$c);
return ( -$b + $root )/(2*$a), ( -$b - $root )/(2*$a);
}</
=={{header|Phix}}==
{{trans|ERRE}}
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">solve_quadratic</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">t3</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">t3</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b</span><span style="color: #0000FF;">-</span><span style="color: #000000;">4</span><span style="color: #0000FF;">*</span><span style="color: #000000;">a</span><span style="color: #0000FF;">*</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">f</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"for a=%g,b=%g,c=%g"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t3</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">t</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">u</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">1e-6</span> <span style="color: #008080;">then</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">switch</span> <span style="color: #7060A8;">sign</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">case</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"single root is %g"</span>
<span style="color: #000000;">u</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">b</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">/</span><span style="color: #000000;">a</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">case</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"real roots are %g and %g"</span>
<span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">-</span><span style="color: #000000;">4</span><span style="color: #0000FF;">*</span><span style="color: #000000;">a</span><span style="color: #0000FF;">*</span><span style="color: #000000;">c</span><span style="color: #0000FF;">/(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)))/</span><span style="color: #000000;">2</span>
<span style="color: #000000;">u</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">f</span><span style="color: #0000FF;">*</span><span style="color: #000000;">b</span><span style="color: #0000FF;">/</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">c</span><span style="color: #0000FF;">/</span><span style="color: #000000;">b</span><span style="color: #0000FF;">/</span><span style="color: #000000;">f</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">case</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"complex roots are %g +/- %g*i"</span>
<span style="color: #000000;">u</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">b</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">/</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">/</span><span style="color: #000000;">a</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">switch</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%-25s the %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">u</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1E9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.4142135</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">}}</span>
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">,</span><span style="color: #000000;">solve_quadratic</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
<pre>
for a=1,b=-1e+9,c=1 the real roots are 1e+9 and 1e-9
Line 1,648 ⟶ 1,959:
=={{header|PicoLisp}}==
<
(de solveQuad (A B C)
Line 1,662 ⟶ 1,973:
(mapcar round
(solveQuad 1.0 -1000000.0 1.0)
(6 .) )</
{{out}}
<pre>-> ("999,999.999999" "0.000001")</pre>
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
declare (c1, c2) float complex,
(a, b, c, x1, x2) float;
Line 1,684 ⟶ 1,995:
put data (x1, x2);
end;
</syntaxhighlight>
=={{header|Python}}==
{{libheader|NumPy}}
This solution compares the naïve method with three "better" methods.
<
import math
Line 1,761 ⟶ 2,072:
print('\nNumpy:')
for c in testcases:
print(("{:.5} "*2).format(*numpy.roots(c)))</
{{out}}
<pre>
Line 1,802 ⟶ 2,113:
=={{header|R}}==
<
r <- sqrt(b * b - 4 * a * c + 0i)
if (abs(b - r) > abs(b + r)) {
Line 1,816 ⟶ 2,127:
qroots(1, -1e9, 1)
[1] 1e+09+0i 1e-09+0i</
Using the builtin '''polyroot''' function (note the order of coefficients is reversed):
<
[1] -1+1i 1-1i
polyroot(c(1, -1e9, 1))
[1] 1e-09+0i 1e+09+0i</
=={{header|Racket}}==
<
(define (quadratic a b c)
(let* ((-b (- b))
Line 1,839 ⟶ 2,150:
;'(0.99999999999995 -1.00000000000005)
;(quadratic 1 0.0000000000001 1)
;'(-5e-014+1.0i -5e-014-1.0i)</
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|Rakudo|2022.12}}
''Works with previous versions also but will return slightly less precise results.''
Raku has complex number handling built in.
<syntaxhighlight lang="raku"
[1, 2, 1],
[1, 2, 3],
[1, -2, 1],
[1, 0, -4],
[1, -
-> @coefficients {
printf "Roots for %d, %d, %d\t=> (%s, %s)\n",
Line 1,858 ⟶ 2,173:
sub quadroots (*[$a, $b, $c]) {
( -$b + $_ ) / (2
( -$b - $_ ) / (2
given
($b
}</
{{out}}
<pre>Roots for 1, 2, 1
Roots for 1, 2, 3
Roots for 1, -2, 1
Roots for 1, 0, -4
Roots for 1, -1000000, 1
=={{header|REXX}}==
Line 1,877 ⟶ 2,192:
<br>(from a default of '''9''') to '''200''' to accommodate when a root is closer to zero than the other root.
Note that only
This REXX version supports ''complex numbers'' for the result.
<
if r1j\=0 then r1=r1||left('+',r1j>0)(r1j/1)"i" /*Imaginary part? Handle complex number*/
if r2j\=0 then r2=r2||left('+',r2j>0)(r2j/1)"i" /* " " " " " */
say ' a =' a /*display the normalized value of A. */
say '
say; say 'root1 ='
say 'root2 ='
exit 0
/*──────────────────────────────────────────────────────────────────────────────────────*/
quad: parse arg aa,bb,cc; numeric digits 200 /*obtain 3 args; use enough dec. digits*/
$= sqrt(bb**2-4*aa*cc); L= length($) /*compute SQRT (which may be complex).*/
r= 1 /(aa+aa); ?= right($, 1)=='i' /*compute reciprocal of 2*aa; Complex?*/
if ? then do; r1= -bb *r; r2=r1; r1j= left($,L-1)*r; r2j=-r1j; end
else do; r1=(-bb+$)*r; r2=(-bb-$)*r; r1j= 0; r2j= 0; end
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x 1 ox; if x=0 then return 0; d= digits(); m.= 9; numeric form
numeric digits 9; h= d+6; x=abs(x); parse value format(x,2,1,,0) 'E0' with g 'E' _ .
g=g*.5'e'_%2; do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
{{out|output|text= when using the input of: <tt> 1 -10e5 1 </tt>}}
<pre>
a = 1
Line 1,917 ⟶ 2,229:
root2 = 0.000001
</pre>
The following output is when Regina 3.9.
<pre>
a = 1
b = -
c = 1
Line 1,930 ⟶ 2,242:
The following output is when R4 REXX is used.
<pre>
a = 1
Line 1,939 ⟶ 2,251:
root2 = 0.0000000001
</pre>
<pre>
a = 3
Line 1,945 ⟶ 2,257:
c = 1
root1 = -0.
root2 = -0.
</pre>
<pre>
a = 1
Line 1,959 ⟶ 2,271:
=== Version 2 ===
<
* 26.07.2913 Walter Pachl
**********************************************************************/
Line 2,021 ⟶ 2,333:
Numeric Digits prec
Return (r+0)
exit: Say arg(1)
Exit</syntaxhighlight>
{{out}}
<pre>
Line 2,039 ⟶ 2,352:
=={{header|Ring}}==
<syntaxhighlight lang="text">
x1 = 0
x2 = 0
Line 2,056 ⟶ 2,369:
x2 = (-b - sqrtDiscriminant) / (2.0*a)
return [x1, x2]
</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}}==
{{works with|Ruby|1.9.3+}}
The CMath#sqrt method will return a Complex instance if necessary.
<
def quadratic(a, b, c)
Line 2,075 ⟶ 2,437:
p quadratic(-2, 7, 15) # [-3/2, 5]
p quadratic(1, -2, 1) # [1]
p quadratic(1, 3, 3) # [(-3 + sqrt(3)i)/2), (-3 - sqrt(3)i)/2)]</
{{out}}
<pre>
Line 2,089 ⟶ 2,451:
=={{header|Run BASIC}}==
<
print "FOR 4,5,6 => ";quad$(4,5,6)
Line 2,100 ⟶ 2,462:
quad$ = str$(x/(2*a)+sqr(d)/(2*a))+" , "+str$(x/(2*a)-sqr(d)/(2*a))
end if
END FUNCTION</
FOR 4,5,6 => -0.625 +i1.05326872 , -0.625 -i1.05326872</pre>
=={{header|Scala}}==
Using [[Arithmetic/Complex#Scala|Complex]] class from task Arithmetic/Complex.
<
object QuadraticRoots {
def solve(a:Double, b:Double, c:Double)={
Line 2,121 ⟶ 2,483:
}
}
}</
Usage:
<
(1.0, 22.0, -1323.0), // two distinct real roots
(6.0, -23.0, 20.0), // with a != 1.0
Line 2,139 ⟶ 2,501:
if(roots._1 != roots._2) println("x2="+roots._2)
println
}</
{{out}}
<pre>a=1.00000 b=22.0000 c=-1323.00
Line 2,165 ⟶ 2,527:
=={{header|Scheme}}==
<
(if (= a 0)
(if (= b 0) 'fail (- (/ c b)))
Line 2,204 ⟶ 2,566:
(quadratic 1 -1e5 1)
; (99999.99999 1.0000000001000001e-05)</
=={{header|Seed7}}==
{{trans|Ada}}
<
include "float.s7i";
include "math.s7i";
Line 2,242 ⟶ 2,604:
r := solve(1.0, -10.0E5, 1.0);
writeln("X1 = " <& r.x1 digits 6 <& " X2 = " <& r.x2 digits 6);
end func;</
{{out}}
Line 2,250 ⟶ 2,612:
=={{header|Sidef}}==
<
[1, 2, 1],
[1, 2, 3],
Line 2,268 ⟶ 2,630:
say ("Roots for #{coefficients}",
"=> (#{quadroots(coefficients...).join(', ')})")
}</
{{out}}
<pre>
Line 2,279 ⟶ 2,641:
=={{header|Stata}}==
<
: polyroots((-2,0,1))
1 2
Line 2,290 ⟶ 2,652:
+-------------------------------+
1 | -1.41421356i 1.41421356i |
+-------------------------------+</
=={{header|Tcl}}==
{{tcllib|math::complexnumbers}}
<
namespace import math::complexnumbers::complex math::complexnumbers::tostring
Line 2,330 ⟶ 2,692:
report_quad -2 7 15 ;# {5, -3/2}
report_quad 1 -2 1 ;# {1}
report_quad 1 3 3 ;# {(-3 - sqrt(3)i)/2), (-3 + sqrt(3)i)/2)}</
{{out}}
<pre>3x**2 + 4x + 1.3333333333333333 = 0
Line 2,358 ⟶ 2,720:
TI-89 BASIC has built-in numeric and algebraic solvers.
<syntaxhighlight lang="text">solve(x^2-1E9x+1.0)</
returns
<pre>x=1.E-9 or x=1.E9</pre>
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-complex}}
<syntaxhighlight lang="wren">import "./complex" for Complex
var quadratic = Fn.new { |a, b, c|
var d = b*b - 4*a*c
if (d == 0) {
// single root
return [[-b/(2*a)], null]
}
if (d > 0) {
// two real roots
var sr = d.sqrt
d = (b < 0) ? sr - b : -sr - b
return [[d/(2*a), 2*c/d], null]
}
// two complex roots
var den = 1 / (2*a)
var t1 = Complex.new(-b*den, 0)
var t2 = Complex.new(0, (-d).sqrt * den)
return [[], [t1+t2, t1-t2]]
}
var test = Fn.new { |a, b, c|
System.write("coefficients: %(a), %(b), %(c) -> ")
var roots = quadratic.call(a, b, c)
var r = roots[0]
if (r.count == 1) {
System.print("one real root: %(r[0])")
} else if (r.count == 2) {
System.print("two real roots: %(r[0]) and %(r[1])")
} else {
var i = roots[1]
System.print("two complex roots: %(i[0]) and %(i[1])")
}
}
var coeffs = [
[1, -2, 1],
[1, 0, 1],
[1, -10, 1],
[1, -1000, 1],
[1, -1e9, 1]
]
for (c in coeffs) test.call(c[0], c[1], c[2])</syntaxhighlight>
{{out}}
<pre>
coefficients: 1, -2, 1 -> one real root: 1
coefficients: 1, 0, 1 -> two complex roots: 0 + i and 0 - i
coefficients: 1, -10, 1 -> two real roots: 9.8989794855664 and 0.10102051443364
coefficients: 1, -1000, 1 -> two real roots: 999.998999999 and 0.001000001000002
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>
=={{header|zkl}}==
zkl doesn't have a complex number package.
{{trans|Elixir}}
<
println("Roots of a quadratic function %s, %s, %s".fmt(a,b,c));
d,a2:=(b*b - 4*a*c), a+a;
Line 2,377 ⟶ 2,856:
println(" the complex roots are %s and \U00B1;%si".fmt(-b/a2,sd/a2));
}
}</
<
quadratic(a,b,c)
}</
{{out}}
<pre>
|