A collection of numeric types and traits for Rust.

Overview

num

crate documentation minimum rustc 1.31 build status

A collection of numeric types and traits for Rust.

This includes new types for big integers, rationals (aka fractions), and complex numbers, new traits for generic programming on numeric properties like Integer, and generic range iterators.

num is a meta-crate, re-exporting items from these sub-crates:

Repository Crate Documentation
num-bigint crate documentation
num-complex crate documentation
num-integer crate documentation
num-iter crate documentation
num-rational crate documentation
num-traits crate documentation
(num-derive) crate documentation

Note: num-derive is listed here for reference, but it's not directly included in num. This is a proc-macro crate for deriving some of num's traits.

Usage

Add this to your Cargo.toml:

[dependencies]
num = "0.4"

Features

This crate can be used without the standard library (#![no_std]) by disabling the default std feature. Use this in Cargo.toml:

[dependencies.num]
version = "0.4"
default-features = false

The num-bigint crate requires the std feature, or the alloc feature may be used instead with Rust 1.36 and later. Other sub-crates may also have limited functionality when used without std.

The libm feature uses pure-Rust floating point implementations in no_std builds, enabling the Float trait and related Complex methods.

The rand feature enables randomization traits in num-bigint and num-complex.

The serde feature enables serialization for types in num-bigint, num-complex, and num-rational.

The num meta-crate no longer supports features to toggle the inclusion of the individual sub-crates. If you need such control, you are recommended to directly depend on your required crates instead.

Releases

Release notes are available in RELEASES.md.

Compatibility

The num crate as a whole is tested for rustc 1.31 and greater.

The num-traits, num-integer, and num-iter crates are individually tested for rustc 1.8 and greater, if you require such older compatibility.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Comments
  • Add BigDecimal Crate

    Add BigDecimal Crate

    Rebase of pull request #193. Addresses issue #8.

    Implementation of BigDecimal, which comprises a BigInt and a u64 scale factor, allowing for storage of 2^64 digits.

    Further implementation is required to set the default maximum precision (so numbers like 1/3 are not represented by 2^64 digits). The current default is 100.

    Add, Sub, Mul implemented by @iterion, I reimplemented Div, Eq, FromStr.

    opened by akubera 33
  • Fix `num-macros` `FromPrimitive` implementation

    Fix `num-macros` `FromPrimitive` implementation

    Current solution follow syntax proposed in rust-lang/rfcs#1681.

    Tracking issue rust-lang/rust#35900

    Close #227

    Code broken after change:

    • [ ] https://github.com/kdar/gameboy-rs
    • [ ] https://github.com/lemonrock/mbedtls
    • [ ] https://github.com/timorantalaiho/kelaa
    • [ ] https://github.com/dylanede/cef-rs
    • [ ] https://github.com/klutzy/aheui-llvm
    • [ ] https://github.com/pcwalton/rust-media
    • [ ] https://github.com/PistonDevelopers/hematite_server
    opened by hauleth 28
  • [RFC] Some performance improvements

    [RFC] Some performance improvements

    I added add and subtract methods that take an operand by value, instead of by reference, so they can work in place instead of always allocating new BigInts for the result.

    I'd like to hear if anyone knows a better way of doing this, though - with the various wrappers/forwardings doing this for all the operations is going to be a mess and add a ton of boilerplate. I haven't even tried to do a complete job of it yet.

    I'm starting to think the sanest thing to do would be to only have in place implements of most of the operations - and have the wrappers clone() if necessary. That way, the only extra work we're doing is a memcpy(), which is a hell of a lot faster than a heap allocation.

    opened by koverstreet 25
  • Implement arithmetic with real for complex

    Implement arithmetic with real for complex

    Hello,

    It might be handy to be able to perform basic arithmetic operations in expressions mixing complex numbers and numeric primitives; see #116. I would be grateful for any feedback, especially regarding the subsets of primitives for which certain operations are implemented.

    Regards, Ivan

    opened by IvanUkhov 18
  • Add doc(html_root_url) and other doc attrs to each crate

    Add doc(html_root_url) and other doc attrs to each crate

    Also update to use https instead of http. This avoids mixed content degradation on docs.rs.

    The doc root URLs are correct as they are, the URL does not include the crate name itself.

    opened by bluss 17
  • Split num into several crates

    Split num into several crates

    Currently num mixes functionality that IMHO should be separate:

    • bigints
    • generic traits (One, Zero, FromPrimitive, ToPrimitive, ...)
    • fractions
    • complex numbers
    • range*

    The biggest offender are bigints, which are implemented very inefficiently. Real-world programs would probably rather use GMP or ramp.

    The best plan of action would probably be creating the smaller crates and deprecating num?

    T-enhancement T-question 
    opened by vks 16
  • Complex struct should be #repr(C)

    Complex struct should be #repr(C)

    The memory layout is probably already identical to C's complex type or std::complex<T>, but it'd be nice to make it explicit. This would help with C interop, and things like real-only FFTs that need to cast real-only vectors into vectors of alternating real/imaginary.

    opened by awelkie 16
  • f32/f64 to Ratio conversion

    f32/f64 to Ratio conversion

    Is there any interest for having conversion from f32/f64 to Ratio? I've implemented that in my code, based on a continued fractions algorithm: https://github.com/sdroege/gst-plugin-rs/blob/d72f1f716b630bc31973fc559c5f5d82255965a1/gst-plugin/src/utils.rs#L53

    The same algorithm is used in GStreamer since a decade or so, for handling framerates stored as a floating point number and similar things, and it generally gives good results, but it's of course not the only way of doing that and depending on the input values another algorithm might find "nicer" results.

    If there's interest, I could prepare a pull request for moving that code over (and generalize it a bit).

    opened by sdroege 14
  • Implementing epsilon function to retrieve EPSILON constant

    Implementing epsilon function to retrieve EPSILON constant

    Hey!

    This PR exposes a new epsilon function in the Float trait so that users can access the EPSILON constant on the float types. I figured as this was such a minimal change it was easier to get a PR in offering the change then write up an issue.

    For me this is a valuable addition. When writing linear algebra or other optimization routines with generic floats we often want to check if some stopping criteria is reached, often something like: (a - b).abs() < eps. Having access to a standard small value would make this a little easier.

    opened by AtheMathmo 14
  • Fix ToPrimitive for f64 -> f32 conversion.

    Fix ToPrimitive for f64 -> f32 conversion.

    Fix ToPrimitive for f64 -> f32 conversion.

    It should use the destination type and not the source type to check if the conversion would be to a value that's in range.

    NOTE: A finite f64 value that is larger than the f32 value range now produces None when converted to f32 with ToPrimitive.

    Previously, too large f64 values would produce inf f32 values. This as cast has an undefined result and was not specified to always produce for example inf.

    The conversion preserves nan/+-inf specifically.

    opened by bluss 14
  • Implemented from_bytes and to_bytes

    Implemented from_bytes and to_bytes

    This commit implements from_bytes and to_bytes methods for BigInt and BigUint. These methods are very useful when working with BigInt types.

    The current code works with big-endian slices/vectors, while the existing code (new() and from_slice()) uses little-endian slices/vectors. My opinion is that big-endian is preferable, but I can change this if necessary.

    opened by gsingh93 14
  • Bump num-family to v1.0?

    Bump num-family to v1.0?

    The num crates are very important to the entire rust ecosystem, and my experience from using them is that they are very mature. But they are all still at v0.x. Is there anything that prevents bumping them all to v1.0?

    opened by HEnquist 5
  • Signed::is_positive and Signed::is_negative implementation/documentation is inconsistent

    Signed::is_positive and Signed::is_negative implementation/documentation is inconsistent

    Based on the documentation:

    /// Returns true if the number is positive and false if the number is zero or negative.
    fn is_positive(&self) -> bool;
    
    /// Returns true if the number is negative and false if the number is zero or positive.
    fn is_negative(&self) -> bool;
    

    However, for signed integer types, we have the following, which matches the documentation:

    #[inline]
    fn is_positive(&self) -> bool { *self > 0 }
    
    #[inline]
    fn is_negative(&self) -> bool { *self < 0 }
    

    But then for floating point types we have:

    /// Returns `true` if the number is positive, including `+0.0` and `INFINITY`
    #[inline]
    fn is_positive(&self) -> bool {
        FloatCore::is_sign_positive(*self)
    }
    
    /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY`
    #[inline]
    fn is_negative(&self) -> bool {
        FloatCore::is_sign_negative(*self)
    }
    

    And so with a simple test like this:

    dbg!(Signed::is_positive(&0i32));
    dbg!(Signed::is_positive(&0.0f32));
    

    We get:

    Signed::is_positive(&0i32) = false
    Signed::is_positive(&0.0f32) = true
    

    I'm not sure what the best approach here (i.e. should 0 count as positive or not for floating point).

    But the behavior should be consistent between floats and ints, and match the documentation on the Signed trait. Otherwise it leads to really subtle and dangerous arithmetic errors.

    opened by Zeenobit 0
  • Human readable (concise) output

    Human readable (concise) output

    The solang compiler uses this crate for integer literals, which can 256 bits in Solidity.

    However formatting bigints with Display is not great.

    contract c {
         int256 constant a = 1e1000;
    }
    

    gives the diagnostic:

    error: literal 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 is too large to fit into type 'int256'

    It would be nice if we had a .to_human_readable() function which would either use e notation or what solc does:

    Error: Type int_const 1000...(993 digits omitted)...0000 is not implicitly convertible to expected type int256. Literal is too large to fit in int256.

    This would work for large numbers which don't consist of lots of zeros too.

    opened by seanyoung 1
  • Trait size of number in bits

    Trait size of number in bits

    I'm interest in having a trait that return the number of bits of T, std only have associated constant, u8::BITS. Similar to num::Bounded.

    Alternative, let n_bits = std::mem::size_of::<T>() * u8::BITS as usize;.

    opened by Stargateur 0
  • Support a more generic binomial coefficients

    Support a more generic binomial coefficients

    Currently binomial coefficient ${n \choose k}$ is implemented when n and k are both integers. However, the generalized binomial coefficient allows n to be any complex number. At least, it's common situation to use binomial coefficients when n is a real number.

    opened by dclong 0
  • Implement rand traits for Ratio ?

    Implement rand traits for Ratio ?

    I'm especially interested in the implementation of Distribution<num::Ratio> for Standard and the UniformSampler backend to use gen_range() on custom types that wrap num::Ratio

    opened by pwnorbitals 2
Owner
null
Human numeric sorting program — does what `sort -h` is supposed to do!

hns — Human Numeric Sort v0.1.0 (⏫︎2022-09-20) © 2022 Fredrick R. Brennan and hns Authors Apache 2.0 licensed, see LICENSE. man page Packages hns_0.1.

Fredrick Brennan 7 Sep 25, 2022
A comprehensive collection of resources and learning materials for Rust programming, empowering developers to explore and master the modern, safe, and blazingly fast language.

?? Awesome Rust Lang ⛰️ Project Description : Welcome to the Awesome Rust Lang repository! This is a comprehensive collection of resources for Rust, a

Shubham Raj 16 May 29, 2023
Collection of immutable and persistent data structures written in Rust, inspired by the standard libraries found in Haskell, Closure and OCaml

PRust: (P)ersistent & Immutable Data Structures in (Rust) This library houses a collection of immutable and persistent data structures, inspired by th

Victor Colombo 13 Aug 13, 2023
Count your code by tokens, types of syntax tree nodes, and patterns in the syntax tree. A tokei/scc/cloc alternative.

tcount (pronounced "tee-count") Count your code by tokens, types of syntax tree nodes, and patterns in the syntax tree. Quick Start Simply run tcount

Adam P. Regasz-Rethy 48 Dec 7, 2022
Unopinionated low level API bindings focused on soundness, safety, and stronger types over raw FFI.

?? firehazard ?? Create a fire hazard by locking down your (Microsoft) Windows so nobody can escape (your security sandbox.) Unopinionated low level A

null 5 Nov 17, 2022
Generate Soufflé Datalog types, relations, and facts that represent ASTs from a variety of programming languages.

treeedb treeedb makes it easier to start writing a source-level program analysis in Soufflé Datalog. First, treeedb generates Soufflé types and relati

Langston Barrett 16 Nov 30, 2022
Provide types for angle manipulation in rust.

angulus Provides types for angle manipulation. Features serde : Serialization/deserialization support via serde. Example use angulus::{*, units::*};

Tristan Guichaoua 2 Sep 2, 2022
Nederlandse programmeertaal. Geinterpreteerd en met dynamische types. Met bytecode compiler en virtual machine, in Rust.

Nederlang Nederlang is een geinterpreteerde programmeertaal, in het Nederlands! Met als bestandsnaam extensie.... .nl! Het maakt gebruik van dynamisch

Danny van Kooten 17 Dec 15, 2022
Choose Rust types at compile-time via boolean constants

condtype Choose Rust types at compile-time via boolean constants, brought to you by Nikolai Vazquez. If you find this library useful, consider starrin

Nikolai Vazquez 36 May 8, 2023
Structopt derived ethers-rs types, useful for building Ethereum CLIs

ethers-structopt Provides ethers-compatible Structopt derives, useful for building Ethereum CLIs. Contributing Pull requests are welcome. For major ch

Georgios Konstantopoulos 6 Dec 27, 2022
Allows processing of iterators of Result types

try-continue try-continue provides one method, try_continue, which allows you to work with iterators of type Result<T, _>, as if they were simply iter

Nick Krichevsky 3 Dec 26, 2021
Utilites for working with `bevy_ecs` when not all types are known at compile time

bevy_ecs_dynamic Utilities for working with bevy_ecs in situations where the types you're dealing with might not be known at compile time (e.g. script

Jakob Hellermann 17 Dec 9, 2022
A tool for determining file types, an alternative to file

file-rs a tool for determining file types, an alternative to file whats done determining file extension determining file type determining file's mime

null 3 Nov 27, 2022
Bam Error Stats Tool (best): analysis of error types in aligned reads.

best Bam Error Stats Tool (best): analysis of error types in aligned reads. best is used to assess the quality of reads after aligning them to a refer

Google 54 Jan 3, 2023
A collection of tools for i3 that assist in window, workspace and output operations.

i3-valet A collection of tools for i3 that assist in window, workspace and output operations. i3-valet can be run directly from the command line or as

Erich Heine 15 Jan 8, 2023
Mirroring remote repositories to s3 storage, with atomic updates and periodic garbage collection.

rsync-sjtug WIP: This project is still under development, and is not ready for production use. rsync-sjtug is an open-source project designed to provi

SJTUG 57 Feb 22, 2023
Just a collection of tiny Rust projects I've did. None warrant a whole repo rn

Daily Rust I try to write some tiny programs daily to gradually improve my Rust skills! Current Program Descriptions first_prog.rs: My first program a

null 3 Nov 5, 2022
Requestty - An easy-to-use collection of interactive cli prompts inspired by Inquirer.js.

Requestty requestty (request-tty) is an easy-to-use collection of interactive cli prompts inspired by Inquirer.js. Easy-to-use - The builder API and m

null 160 Dec 28, 2022
A collection of semi-useful tools made for GNU/Linux

DECTOOLS A collection of semi-useful tools made for GNU/Linux. Some may work on macOS, though functionality isn't a priority. Depenencies: python, bas

Decator 3 Jun 8, 2022