Skip to content

Instantly share code, notes, and snippets.

@mwlon
Created September 6, 2025 00:44
Show Gist options
  • Select an option

  • Save mwlon/dc34bc85d5df7959532b081fdfb00dec to your computer and use it in GitHub Desktop.

Select an option

Save mwlon/dc34bc85d5df7959532b081fdfb00dec to your computer and use it in GitHub Desktop.
Recurse Center Symbolic Differentiation
type Real = f32;
#[derive(Clone, Debug)]
struct Polynomial(Vec<Real>);
impl Polynomial {
fn empty() -> Self {
Self(vec![])
}
fn derive(&self) -> Self {
if self.0.len() == 0 {
Self::empty()
} else {
let new_coeffs = self.0[1..]
.iter()
.enumerate()
.map(|(new_pow, &coeff)| coeff * (new_pow as Real + 1.0))
.collect();
Self(new_coeffs)
}
}
}
fn main() {
// 3 + 4x + 5x^2 + 6x^3
let mut expression = Polynomial(vec![3.0, 4.0, 5.0, 6.0]);
for _ in 0..6 {
println!("{:?}", expression);
expression = expression.derive();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment