Last active
October 10, 2019 12:02
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)") | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
printRoots(a: 1.0, b: 3.0, c: -4.0)
1.0
-4.0