Skip to content

Instantly share code, notes, and snippets.

@lanserxt
Last active October 10, 2019 12:02
Show Gist options
  • Select an option

  • Save lanserxt/e005ea22058e8435245bf971eefa3962 to your computer and use it in GitHub Desktop.

Select an option

Save lanserxt/e005ea22058e8435245bf971eefa3962 to your computer and use it in GitHub Desktop.
Quadric equation roots printing method. There were to restrictions on type and ranges so it's a basic example.
func printRoots(a: Double, b: Double, c: Double, showImaginaryRoots: Bool = false) {
let b2 = b * b
let disc = b2 - (4 * a * c)
let discSqrt = sqrt(fabs(disc))
let isImage = disc < 0
let result = b * b - 4.0 * a * c
guard result >= 0.0 else {
print("no roots")
return
}
if isImage {
if showImaginaryRoots {
print("(\(-b) + \(discSqrt)i)/\(2*a)\n(\(-b) - \(discSqrt)i)/\(2*a)")
} else {
print("no roots")
}
} else {
let top = -b + discSqrt
guard top != 0 else {
print("no roots")
return
}
let bottom = 2 * a
let total = top / bottom
let top2 = -b - discSqrt
let total2 = top2 / bottom
print("\(total)\n\(total2)")
}
}
@lanserxt

Copy link
Copy Markdown
Author

printRoots(a: 1.0, b: 3.0, c: -4.0)

1.0
-4.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment