#fraction #type #static #data-type #numeric

nightly staticfraction

numeric data types that represent fractions; generalized fixed-point numbers

1 unstable release

Uses old Rust 2015

0.0.1 Jun 7, 2017

#25 in #data-type

GPL-3.0 license

16KB
150 lines

Static fractions

Static fractions, as introduced in this crate, are numeric data types that represent a fraction, store their numerator in memory and their denominator in code. They are a generalization of fixed-point numbers.

For example (and not all of this is implemented yet):

// The range 0-255 means voltages from 0V (0/1) to 1.25V (125/100).
StaticFractionType!(VoltageFromADC, 0u8, 255u8, 0, 1, 125, 100);

fn adc_read() -> VoltageFromADC {
    let adc_readout: u8 = lowlevel_adc_read();
    VoltageFromADC::new_from_stored(adc_readout)
}

let current = static_fraction(10, 1000); // 10mA
let resistance_at_zero = 100; // 100ohm
let resistance_per_deg = static_fraction(4, 100); // 0.04ohm/degC

let resistance = adc_read() / current;
let temperature = 0 + (resistance - resistance_at_zero) / resistance_per_deg; // in degC

if temperature > 30 { fan_on(); }
if temperature < 20 { fan_off(); }

The idea is that

  • raw data can be stored in as compact a data type as it arrives
  • any datum can be used in calculations without needing to know more than its unit
  • all operations can be performed in integer arithmetic (so they don't pull floating point emulation onto devices without floating point support)
  • possibly, intermediate results can be stored in a compact way (where it's as of now completely unclear how the tradeof between precision and storage will be decided)

State of the crate

This project is in a very early state, in which it first tries to demonstrate that what is to be achieved is possible in Rust.

So far, comparisons between different fractions are almost fully implemented, showing how each fraction type's parameters are stored and accessed.

Dependencies

~385–620KB
~13K SLoC