Skip to content

Conversation

@ladezai
Copy link

@ladezai ladezai commented Dec 10, 2025

Hi, just wanted to share a minor improvement in src/function/evaluate.rs. The function polynomial is shorter and addresses the edge case n == 0 directly, no branching needed.

For any further modification feel free to comment/change. Any feedback is appreciated.

Details

I used the following code on rust playground (with release compile flag), and it seems to perform the same in terms of time execution.

use std::time::Instant;

pub fn polynomial(z: f64, coeff: &[f64]) -> f64 {
    let n = coeff.len();
    if n == 0 {
        return 0.0;
    }

    let mut sum = *coeff.last().unwrap();
    for c in coeff[0..n - 1].iter().rev() {
        sum = *c + z * sum;
    }
    sum
}

pub fn polynomial2(z: f64, coeff: &[f64]) -> f64 {
    coeff.into_iter().rev().fold(0_f64, |acc, val| acc * z + val)
}

pub fn main() {
    println!("Edge case with an empty coeff: {:?}", polynomial2(321.231231_f64, &[]));

    let (z, coeffs) = (32.12, [3.0_f64, -2.0_f64, 7.0_f64, 123.0_f64, 12.1_f64]);
    let now = Instant::now();
    for _i in 0.. 100 {
        polynomial(z, &coeffs);
    }
    let elapsed = now.elapsed();
    println!("Polynomial 1: {elapsed:?}");
    
    let now = Instant::now();
    for _i in 0.. 100 {
        polynomial2(z, &coeffs);
    }
    let elapsed = now.elapsed();
    println!("Polynomial 2: {elapsed:?}");
    
    let now = Instant::now();
    for _i in 0.. 100 {
        polynomial(z, &coeffs);
    }
    let elapsed = now.elapsed();
    println!("Polynomial 1: {elapsed:?}");

    println!("Difference: {:?}", polynomial(z, &coeffs) - polynomial2(z, &coeffs));
}

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant