Solving Quadratic Equations in Julia- A Step-by-Step Tutorial
What This Article Covers
Quadratic equations look like ax² + bx + c = 0. Julia handles them fast. This tutorial shows you exactly how to solve them with code you can copy and run.
If you want the quick version: use the quadratic formula directly or use Julia's built-in polynomial functions. Both methods work. I'll show you both.
Quick Refresher: The Quadratic Formula
You probably learned this in school. The solutions are:
x = (-b ± √(b² - 4ac)) / 2a
The part under the square root is the discriminant: b² - 4ac. It tells you what kind of solutions you'll get:
- Positive discriminant: two real solutions
- Zero discriminant: one real solution
- Negative discriminant: two complex solutions
Setting Up Julia
I'm assuming you have Julia installed. If not, download it from julialang.org. The installation takes about 5 minutes.
Start the REPL and you're ready to code. No extra packages needed for the basics—the standard library handles complex numbers natively.
Method 1: Direct Implementation
Here's the most straightforward approach. No tricks, no shortcuts—just the math written as code.
Basic Function
function solve_quadratic(a, b, c)
discriminant = b^2 - 4*a*c
if discriminant >= 0
x1 = (-b + sqrt(discriminant)) / (2*a)
x2 = (-b - sqrt(discriminant)) / (2*a)
return (x1, x2)
else
# Handle complex roots
real_part = -b / (2*a)
imag_part = sqrt(-discriminant) / (2*a)
x1 = complex(real_part, imag_part)
x2 = complex(real_part, -imag_part)
return (x1, x2)
end
end
Testing It
# Example: 2x² + 5x - 3 = 0
solutions = solve_quadratic(2, 5, -3)
println("x₁ = $(solutions[1]), x₂ = $(solutions[2])")
This gives you x₁ = 0.5 and x₂ = -3.0. Verify: 2(0.5)² + 5(0.5) - 3 = 0 ✓
Method 2: Using Polynomials Package
Julia has a Polynomials package that handles this for you. Install it once, use it forever.
using Pkg
Pkg.add("Polynomials")
using Polynomials
# Create polynomial: 2x² + 5x - 3
p = Polynomial([2, 5, -3])
# Get roots directly
roots(p)
This returns the same answers. The package is useful when you're working with higher-degree polynomials too.
Method 3: Using the Roots Package
The Roots package specializes in finding zeros. It's overkill for simple quadratics but handles messy equations well.
Pkg.add("Roots")
using Roots
f(x) = 2x^2 + 5x - 3
# Find all roots
find_zeros(f, -10, 10)
This searches for roots in the interval [-10, 10]. It's slower than the direct formula but works when you don't know where the roots are.
Comparing the Methods
| Method | Speed | Complex Roots | Best For |
|---|---|---|---|
| Direct formula | Fastest | Yes (manual) | Simple cases, learning |
| Polynomials package | Fast | Yes (automatic) | Multiple polynomials |
| Roots package | Slower | Yes | Non-polynomial equations |
Common Mistakes to Avoid
- Dividing by zero: If a = 0, you don't have a quadratic equation. Add a check for it.
- Integer overflow: For huge coefficients, use Float64 explicitly:
float(a) - Precision issues: For high-precision work, use BigFloat:
big(2)^2
Robust Version with Error Handling
function solve_quadratic_safe(a, b, c)
if a == 0
error("Not a quadratic equation (a = 0)")
end
discriminant = b^2 - 4*a*c
denom = 2*a
if discriminant == 0
return (-b / denom, nothing) # One solution
elseif discriminant > 0
return ((-b + sqrt(discriminant)) / denom,
(-b - sqrt(discriminant)) / denom)
else
real_part = -b / denom
imag_part = sqrt(-discriminant) / denom
return (complex(real_part, imag_part),
complex(real_part, -imag_part))
end
end
Real-World Example
Say you're calculating projectile motion. An object follows -4.9t² + 20t + 5 = 0. When does it hit the ground?
solutions = solve_quadratic(-4.9, 20, 5)
ground_time = filter(x -> x > 0 && imag(x) == 0, solutions)
println("Object hits ground at t = $(ground_time[1]) seconds")
Result: approximately 4.54 seconds. The negative solution (-0.22) gets discarded since negative time is meaningless.
Quick Start Checklist
- Open Julia REPL
- Copy the
solve_quadraticfunction above - Test with:
solve_quadratic(1, -5, 6)→ expect x = 2 and x = 3 - Verify manually: 1(2)² - 5(2) + 6 = 0 ✓
Bottom Line
For quadratic equations in Julia, the direct formula is your best bet. It's fast, accurate, and doesn't require dependencies. Install the Polynomials package only if you're also dealing with cubic or quartic equations.