Crates.io | linear_isomorphic |
lib.rs | linear_isomorphic |
version | 0.2.4 |
source | src |
created_at | 2024-06-22 23:29:45.652596 |
updated_at | 2024-08-20 16:35:47.06421 |
description | A set of traits to astract over linear-like types. |
homepage | |
repository | |
max_upload_size | |
id | 1280862 |
size | 7,797 |
This crate defines a trait to identify when types can be treated as linear objects. Many algorithms can be written generically over many types but often times crates implement their own linear algebra types over and over again to guarantee some kind of functionality.
This crate aims to allow algorithms to be agnostic about the specific representation of vector types. For example, many geoemtric operations can be performed without knowledge of the dimension or vector type:
use linear_isomorphic::*;
pub fn point_segment_distance<Vec>(start: &Vec, end: &Vec, point: &Vec) -> f32
where
Vec: VectorSpace<Scalar = f32>,
{
let dir = *end - *start;
let t = (*point - *start).dot(&dir) / dir.norm_squared();
let t = t.clamp(0.0, 1.0);
let closest = *start + dir * t;
(closest - *point).norm()
}
Or even numerical multivariate calculus:
use std::{
fmt::Debug,
ops::{AddAssign, Div, Mul},
};
use linear_isomorphic::*;
pub fn numerical_derivative<T, F>(x: f32, f: &F) -> T
where
T: LinAlg<f32>,
f32: Mul<T, Output = T>,
F: Fn(f32) -> T,
{
let mul = <f32 as Mul<f32>>::mul;
let h = mul(1e-3, f32::max(f32::abs(x), 1.0));
let denom = h + h;
let num = f(x + h) - f(x - h);
<T as Div<f32>>::div(num, denom)
}
Suggestions to make the traits defined in this crate more robust are always welcomed.