Sling Academy
Home/Rust/Implementing Quadratic Equations and Polynomial Evaluations in Rust

Implementing Quadratic Equations and Polynomial Evaluations in Rust

Last updated: January 03, 2025

Rust, being a memory-safe system programming language, is great for numerical computations due to its performance and reliability. In this article, we will explore how to implement quadratic equations and general polynomial evaluations in Rust.

Understanding Quadratic Equations

A quadratic equation is a second-order polynomial in a single variable with three coefficients: a, b, and c. It is generally written as:

a * x2 + b * x + c = 0

The solutions for x can be found using the quadratic formula:

x = (-b ± √(b2 - 4ac)) / (2a)

Implementing a Quadratic Solver in Rust

Let's start by implementing a quadratic solver in Rust:

fn solve_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
    let discriminant = b.powi(2) - 4.0 * a * c;
    if discriminant > 0.0 {
        // Two real solutions
        let sqrt_discriminant = discriminant.sqrt();
        vec![
            (-b + sqrt_discriminant) / (2.0 * a),
            (-b - sqrt_discriminant) / (2.0 * a),
        ]
    } else if discriminant == 0.0 {
        // One real solution
        vec![
            -b / (2.0 * a)
        ]
    } else {
        // No real solution
        vec![]
    }
}

This function calculates the discriminant (b^2 - 4ac) to determine the nature of the roots, switching between returning two roots in the case of a positive discriminant, one root for zero discriminant, and an empty vector when the discriminant is negative.

Polynomial Evaluations

Beyond quadratic equations, Rust can also handle polynomial evaluations of any degree. Evaluating polynomials is a combination of computational efficiency and accuracy.

A general polynomial can be expressed as:

P(x) = a_n * x^n + a_(n-1) * x^(n-1) + ... + a_1 * x + a_0

Implementing a Polynomial Evaluator in Rust

The Horner’s method is an efficient algorithm to evaluate a polynomial:

fn evaluate_polynomial(coeffs: &[f64], x: f64) -> f64 {
    coeffs.iter().rev().fold(0.0, |acc, &coeff| acc * x + coeff)
}

The evaluate_polynomial function uses Horner's rule to compute polynomial values efficiently by reducing the number of multiplications. This works by restructuring the polynomial expression to minimize complexity, drastically improving performance for large-scale polynomials.

Putting It All Together

Let's see both of these implementations in action with a complete example. This will demonstrate how you might solve quadratic equations and evaluate a polynomial:

fn main() {
    // Solving a quadratic equation
    let a = 1.0;
    let b = -3.0;
    let c = 2.0;
    let solutions = solve_quadratic(a, b, c);
    println!("Solutions: {:?}", solutions);

    // Evaluating a polynomial
    let coeffs = vec![3.0, 0.0, -4.0, 2.0];
    let x = 2.0;
    let result = evaluate_polynomial(&coeffs, x);
    println!("Polynomial result: {}", result);
}

In this complete example, solve_quadratic is used to find roots of the quadratic equation x^2 - 3x + 2 = 0, and evaluate_polynomial calculates the value of the polynomial 3x^3 - 4x + 2 for x=2. Such implementations are smooth in Rust due to its expressiveness and efficiency.

Conclusion

Solving quadratic equations and evaluating polynomials are fundamental operations that can serve as building blocks for more complex numerical computations. Rust's powerful language features and safety make it a superb choice for such tasks. Whether you're simply curious or want to extend these ideas into larger projects, Rust provides an excellent floor for robust solution development in numerical methods.

Next Article: Building a Simple Math Interpreter in Rust

Previous Article: Creating and Using a Rust Enum for Numeric Error Handling

Series: Math and Numbers in Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior