From ad4c09192e6144e3e914748f9ce4edf371cf75b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Manuel=20Tom=C3=A1s?= Date: Thu, 7 Jan 2021 11:57:02 -0300 Subject: Initial commit Starting off with a function able to turn recursive linear interpolations into their corresponding polynomial. --- .gitignore | 1 + Cargo.lock | 5 +++++ Cargo.toml | 9 +++++++++ src/lib.rs | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 5 +++++ 5 files changed, 73 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 src/lib.rs create mode 100644 src/main.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..b1c5475 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,5 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "poly" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..ab64b5d --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "poly" +version = "0.1.0" +authors = ["Juan Manuel Tomás "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..31f230e --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,53 @@ +pub type Number = f32; + +pub type Poly = Vec; + +#[derive(Debug)] +pub enum Lerp { + Node(Box, Box), + Leaf(Number, Number) +} + +impl Lerp { + pub fn new(v: Vec) -> Box { + Lerp::new_s(&v[..]) + } + + fn new_s(v: &[Number]) -> Box { + match v.len() { + 0 => Box::new(Lerp::Leaf(0.0, 0.0)), + 1 => Box::new(Lerp::Leaf(v[0], v[0])), + 2 => Box::new(Lerp::Leaf(v[0], v[1])), + _ => Box::new(Lerp::Node(Lerp::new_s(&v[0..v.len() - 1]), Lerp::new_s(&v[1..v.len()]))) + } + } +} + +pub fn lp(l: Box) -> Poly { + match *l { + Lerp::Leaf(a, b) => vec![a, b - a], + Lerp::Node(a, b) => { + let a = lp(a); + let b = lp(b); + let c = poly_sub(&b, &a); + skewed_sum(a, c) + } + } +} + +fn poly_sub(a: &Poly, b: &Poly) -> Poly { + let mut r = a.clone(); + for i in 0..r.len() { + r[i] -= b[i]; + } + r +} + +fn skewed_sum(a: Poly, b: Poly) -> Poly { + let mut r = a.clone(); + for i in 0..r.len() - 1 { + r[i + 1] += b[i]; + } + r.push(b[b.len() - 1]); + r +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..1e4f704 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,5 @@ +fn main() { + let a = poly::Lerp::new(vec![1.0, 5.0, 8.0, 3.0, 10.0]); + println!("{:?}", a); + println!("{:?}", poly::lp(a)); +} -- cgit v1.2.3