Roots of a quadratic function: Difference between revisions

Content added Content deleted
(+Stata)
Line 1,148: Line 1,148:
Alternative solutions might make use of Julia's Polynomials or Roots packages.
Alternative solutions might make use of Julia's Polynomials or Roots packages.


<lang julia>function quadroots(x::Real, y::Real, z::Real)
<lang Julia>
a, b, c = promote(float(x), y, z)
function quad_roots{S<:Real,T<:Real,U<:Real}(x::S, y::T, z::U)
(a, b, c) = promote(float(x), y, z)
if a 0.0 return [-c / b] end
2eps(a) < abs(a) || return [-c/b]
Δ = b ^ 2 - 4a * c
if Δ 0.0 return [-sqrt(c / a)] end
disc = b^2 - 4a*c
2eps(b^2) < abs(disc) || return [-sqrt(c/a)]
if Δ < 0.0 Δ = complex(Δ) end
if disc < 0
d = sqrt(Δ)
disc += 0.0im
if b < 0.0
end
d -= b
d = sqrt(disc)
return [d / 2a, 2c / d]
if b < 0
d += -b
return [d/2a, 2c/d]
else
else
d = -b - d
d = -d - b
return [2c/d, d/2a]
return [2c / d, d / 2a]
end
end
end
end


a = {1, 1, 1.0, 10}
a = [1, 1, 1.0, 10]
b = {10, 2, -10.0^9, 1}
b = [10, 2, -10.0 ^ 9, 1]
c = {1, 1, 1, 1}
c = [1, 1, 1, 1]


for i in 1:length(a)
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), ", ")
pstr = @sprintf "%fx^2 + %fx + %f" a[i] b[i] c[i]
end</lang>
println("The roots of ", pstr, " are: ")
println(" ", join(quad_roots(a[i], b[i], c[i]), " and "), "\n")
end
</lang>


{{out}}
{{out}}
<pre>The roots of 1.00x² + 10.00x + 1.00
<pre>
x₀ = (-0.1, -9.9)
The roots of 1.000000x^2 + 10.000000x + 1.000000 are:
The roots of 1.00x² + 2.00x + 1.00
-0.10102051443364381 and -9.898979485566356
x₀ = (-1.0)

The roots of 1.000000x^2 + 2.000000x + 1.000000 are:
The roots of 1.00x² + -1000000000.00x + 1.00
-1.0
x₀ = (1.0e9, 0.0)
The roots of 10.00x² + 1.00x + 1.00

x₀ = (-0.05 + 0.31im, -0.05 - 0.31im)</pre>
The roots of 1.000000x^2 + -1000000000.000000x + 1.000000 are:
1.0e9 and 1.0e-9

The roots of 10.000000x^2 + 1.000000x + 1.000000 are:
-0.05 + 0.3122498999199199im and -0.05 - 0.3122498999199199im
</pre>


=={{header|Kotlin}}==
=={{header|Kotlin}}==