6 releases

0.3.2 Nov 25, 2020
0.3.1 Oct 21, 2020
0.2.0 Oct 12, 2020
0.1.1 Oct 12, 2020

#623 in Math

22 downloads per month
Used in prepona

MIT license

61KB
581 lines

Logo by www.freepik.com

Magnitude - To infinity and beyond!

Crate API
This crate is useful when you need to work with algorithms like Dijkstra's Shortest Path or Floyd–Warshall algorithm that require infinite values in order to be written elegantly.

One simple example can be finding the max value in a vector:

use magnitude::Magnitude;

fn find_max(vec: &Vec<Magnitude<i32>>) -> Magnitude<i32> {
    let mut max = Magnitude::NegInfinite;
    for val in vec {
        if *val > max {
            max = *val;
        }
    }

    max
}

let vec: Vec<Magnitude<i32>> = vec![2.into(), 3.into(), 6.into(), (-10).into()];
assert_eq!(find_max(&vec), 6.into());

You can do all valid comparison(==, !=, >, <, >=, <=) and arithmetic(+,-, *, /, +=, -=, *=, /=) operations on magnitudes.
Invalid operations are listed below which means any other operation is valid.

Invalid operations

  • Comparison:
    • two PosInfinite
    • two NegInfinite
  • Arithmetic:
    • Add:
      • PosInfinite + NegInfinite
    • Sub:
      • PosInfinite - PosInfinite
      • NegInfinite - NegInfinite
    • Mul:
      • zero * PosInfinite
      • zero * NegInfinite
    • Div:
      • non-zero / PosInfinite
      • non-zero / NegInfinite
      • PosInfinite / zero
      • NegInfinite / zero
      • PosInfinite / PosInfinite
      • PosInfinite / NegInfinite
      • NegInfinite / PosInfinite
      • NegInfinite / NegInfinite

Relationship of Magnitude with f64 and f32 infinities

Magnitude as of 0.2.0 treat f64::INFINITY, f64::NEG_INFINITY, f32::INFINITY, f32::NEG_INFINITY as infinites:

use magnitude::Magnitude;

let pos_inf: Magnitude<f64> = f64::INFINITY.into();
let neg_inf: Magnitude<f64> = f64::NEG_INFINITY.into();
assert!(pos_inf.is_pos_infinite());
assert!(neg_inf.is_neg_infinite());

let pos_inf: Magnitude<f32> = f32::INFINITY.into();
let neg_inf: Magnitude<f32> = f32::NEG_INFINITY.into();
assert!(pos_inf.is_pos_infinite());
assert!(neg_inf.is_neg_infinite());

Release

  • 0.3.2: Enforce Copy instead of Clone.
  • 0.3.1: Fixed is_finite() bug.
  • 0.3.0:
    • add from_vec to build a vector of Magnitude from a vector of values:
      use magnitude::Magnitude;
      
      let magnitude_vec = Magnitude::from_vec(&vec![1,2,3]);
      
      assert_eq!(magnitude_vec[0], 1.into());
      assert_eq!(magnitude_vec[1], 2.into());
      assert_eq!(magnitude_vec[2], 3.into());
      
    • add unwrap for easier access to value inside Finite:
      use magnitude::Magnitude;
      
      let one: Magnitude<i32> = 1.into();
      
      assert_eq!(one.unwrap(), 1);
      
  • 0.2.0: handle f64::INFINITY, f64::NEG_INFINITY, f32::INFINITY, f32::NEG_INFINITY properly
    special thanks to @niklasmohrin and @smarnach

Dependencies

~155KB