Coder Social home page Coder Social logo

Comments (1)

erikmannerfelt avatar erikmannerfelt commented on July 29, 2024

(For future reference, I'm using this tool because I think it's fun and I just found it)

I asked for a re-write without using unwrap:

fn interpolate(x: &Vec<f64>, y: &Vec<f64>, x_new: &Vec<f64>) -> Vec<f64> {
    let mut y_new: Vec<f64> = Vec::with_capacity(x_new.len());

    for &x_star in x_new {
        if x_star <= x[0] {
            // Linear extrapolation to the left
            y_new.push(y[0] + (x_star - x[0]) * (y.get(1).unwrap_or(&y[0]) - y[0]) / (x.get(1).unwrap_or(&x[0]) - x[0]));
        } else if x_star >= *x.last().unwrap_or(&0.0) {
            // Linear extrapolation to the right
            let n = x.len() - 1;
            y_new.push(
                y[n] + 
                (x_star - x[n]) * 
                (y.get(n).unwrap_or(&y[n-1]) - y.get(n-1).unwrap_or(&0.0)) / 
                (x[n] - x.get(n-1).unwrap_or(&0.0))
            );
        } else {
            // Linear interpolation in-between
            for (i, &xi) in x.iter().enumerate() {
                if xi >= x_star {
                    y_new.push(
                        y[i-1] +
                        (x_star - x[i-1]) *
                        (y[i] - y[i-1]) /
                        (x[i] - x[i-1])
                    );
                    break;
                }
            }
        }
    }

    y_new
}

from rsgpr.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.