2 releases

new 0.1.1 Apr 14, 2024
0.1.0 Apr 14, 2024

#515 in Math

GPL-3.0-or-later

12KB
307 lines

fixedpoint

Fixed-point numbers with an underlying type and precision divisor.

Generally this is a power of 10 but you can do other things, like 256 to use a lower byte etc. Presumably the compiler optimises operations to use shifting instead of division/multiplication here.

// use it directly
let x = Fixed<u8, 10>::from(5.3f64);
println!("{}", x * 2); // 10.6

// have a wrapper that controls what operations can be done
// useful for units of measurement that have special semantics
// for example, multiplying lengths gives an area.
struct Length(Fixed<u16, 100>);
struct Area(Fixed<u32, 100>);

impl Mul for Length {
	type Output = Area;

	fn mul(self, rhs: Self) -> Area {
		Area((self.0 * rhs.0).into())
	}
}

Dependencies

~155KB