Roots of a quadratic function: Difference between revisions
Content added Content deleted
Line 1,492: | Line 1,492: | ||
IO.Put("X1 = " & Fmt.LongReal(r[1]) & " X2 = " & Fmt.LongReal(r[2]) & "\n"); |
IO.Put("X1 = " & Fmt.LongReal(r[1]) & " X2 = " & Fmt.LongReal(r[2]) & "\n"); |
||
END Quad.</lang> |
END Quad.</lang> |
||
=={{header|Nim}}== |
|||
<lang nim>import complex |
|||
import math |
|||
import strformat |
|||
func quadRoots(a, b, c: float): array[2, Complex[float]] = |
|||
var (a, b, c) = (a, b, c) |
|||
b /= a |
|||
c /= a |
|||
var Δ = b ^ 2 - 4 * a * c |
|||
if Δ == 0.0: |
|||
return [complex(-c / b), complex(0.0)] |
|||
var d = sqrt(complex(Δ)) |
|||
if b < 0.0: |
|||
d -= complex(b) |
|||
return [d / complex(2.0 * a), complex(2.0 * c) / d] |
|||
else: |
|||
d = -d - b |
|||
return [complex(2 * c) / d, d / complex(2 * a)] |
|||
var a = [2.0, 1.0, 1.0, 10.0] |
|||
var b = [10.0, 2.0, -10.0 ^ 9, 1] |
|||
var c = [1.0, 1.0, 1.0, 1.0] |
|||
var coefficients = newSeq[tuple[a, b, c: float]]() |
|||
for i in 0..3: |
|||
coefficients.add((a[i], b[i], c[i])) |
|||
for (x, y, z) in coefficients: |
|||
echo &"The roots for {x:.2f}x² + {y:.2f}x + {z:.2f}" |
|||
echo &"\tx₀ = ", quadRoots(x, y, z)</lang> |
|||
{{out}} |
|||
<pre> |
|||
The roots for 2.00x² + 10.00x + 1.00 |
|||
x₀ = [(-0.10435607626104, -0.0), (-2.39564392373896, 0.0)] |
|||
The roots for 1.00x² + 2.00x + 1.00 |
|||
x₀ = [(-0.5, 0.0), (0.0, 0.0)] |
|||
The roots for 1.00x² + -1000000000.00x + 1.00 |
|||
x₀ = [(1000000000.0, 0.0), (1e-09, 0.0)] |
|||
The roots for 10.00x² + 1.00x + 1.00 |
|||
x₀ = [(-0.005000000000000001, 0.09987492177719091), (-0.005, -0.0998749217771909)] |
|||
</pre> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |