Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a simpler, easier to use interface for simpler problems #20

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

koute
Copy link

@koute koute commented Dec 20, 2023

The default interface for this crate is somewhat tricky to use, especially if you want to just run Levenberg-Marquardt to pick coefficients for a simple equation with only one input and one output, so I've come up with a little helper for my own use to make things a little bit more convenient, and I thought it might be worth upstreaming it.

Here's how it's used: (assuming y = f(ws, x), where ws are the coefficients we want to calculate)

use levenberg_marquardt::Equation;

struct Problem;

impl Equation<2, f64> for Problem {
    fn equation(&self, ws: &[f64; 2], x: f64) -> f64 {
        ws[0] * 2.0 * x + ws[1] * 0.5 * x.powi(2)
    }

    fn derivatives(&self, ws: &[f64; 2], x: f64) -> [f64; 2] {
        [
            2.0 * x,
            0.5 * x.powi(2),
        ]
    }
}

let ws = [1.33, 0.66];
let xs = [1.0, 10.0, 100.0];
let ys = xs.map(|x| Problem.equation(&ws, x));
let ([w0, w1], _) = Problem.least_squares_fit(&xs, &ys, [1.5, 1.0]);
assert_relative_eq!(w0, 1.33);
assert_relative_eq!(w1, 0.66);

As you can see it's dead simple to use and it doesn't require any nalgebra acrobatics as it only uses plain old slices and arrays to pass data.

Feel free to close this PR if you feel this is unnecessary.

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