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) |
|||
if a ≈ 0.0 return [-c / b] end |
|||
Δ = b ^ 2 - 4a * c |
|||
⚫ | |||
disc = b^2 - 4a*c |
|||
if Δ < 0.0 Δ = complex(Δ) end |
|||
d = sqrt(Δ) |
|||
if b < 0.0 |
|||
d -= b |
|||
d |
return [d / 2a, 2c / d] |
||
if b < 0 |
|||
d += -b |
|||
⚫ | |||
else |
else |
||
d = - |
d = -d - b |
||
return [2c/d, d/2a] |
return [2c / d, d / 2a] |
||
end |
end |
||
end |
end |
||
a = |
a = [1, 1, 1.0, 10] |
||
b = |
b = [10, 2, -10.0 ^ 9, 1] |
||
c = |
c = [1, 1, 1, 1] |
||
for |
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] |
|||
⚫ | |||
println("The roots of ", pstr, " are: ") |
|||
println(" ", join(quad_roots(a[i], b[i], c[i]), " and "), "\n") |
|||
end |
|||
⚫ | |||
{{out}} |
{{out}} |
||
⚫ | |||
<pre> |
|||
x₀ = (-0.1, -9.9) |
|||
⚫ | |||
⚫ | |||
-0.10102051443364381 and -9.898979485566356 |
|||
x₀ = (-1.0) |
|||
The roots of 1. |
The roots of 1.00x² + -1000000000.00x + 1.00 |
||
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 |
|||
⚫ | |||
-0.05 + 0.3122498999199199im and -0.05 - 0.3122498999199199im |
|||
</pre> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |