num-rational-0.2.2/.gitignore010066400247370024737000000000221343362654300143630ustar0000000000000000Cargo.lock target num-rational-0.2.2/Cargo.toml.orig010066400247370024737000000022161347757155700153050ustar0000000000000000[package] authors = ["The Rust Project Developers"] description = "Rational numbers implementation for Rust" documentation = "https://docs.rs/num-rational" homepage = "https://github.com/rust-num/num-rational" keywords = ["mathematics", "numerics"] categories = ["algorithms", "data-structures", "science", "no-std"] license = "MIT/Apache-2.0" name = "num-rational" repository = "https://github.com/rust-num/num-rational" version = "0.2.2" readme = "README.md" build = "build.rs" exclude = ["/ci/*", "/.travis.yml", "/bors.toml"] [package.metadata.docs.rs] features = ["std", "bigint-std", "serde"] [dependencies] [dependencies.num-bigint] optional = true version = "0.2.0" default-features = false [dependencies.num-integer] version = "0.1.38" default-features = false [dependencies.num-traits] version = "0.2.7" default-features = false [dependencies.serde] optional = true version = "1.0.0" default-features = false [features] default = ["bigint-std", "std"] i128 = ["num-integer/i128", "num-traits/i128"] std = ["num-integer/std", "num-traits/std"] bigint = ["num-bigint"] bigint-std = ["bigint", "num-bigint/std"] [build-dependencies] autocfg = "0.1.3" num-rational-0.2.2/Cargo.toml0000644000000032170000000000000115030ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "num-rational" version = "0.2.2" authors = ["The Rust Project Developers"] build = "build.rs" exclude = ["/ci/*", "/.travis.yml", "/bors.toml"] description = "Rational numbers implementation for Rust" homepage = "https://github.com/rust-num/num-rational" documentation = "https://docs.rs/num-rational" readme = "README.md" keywords = ["mathematics", "numerics"] categories = ["algorithms", "data-structures", "science", "no-std"] license = "MIT/Apache-2.0" repository = "https://github.com/rust-num/num-rational" [package.metadata.docs.rs] features = ["std", "bigint-std", "serde"] [dependencies.num-bigint] version = "0.2.0" optional = true default-features = false [dependencies.num-integer] version = "0.1.38" default-features = false [dependencies.num-traits] version = "0.2.7" default-features = false [dependencies.serde] version = "1.0.0" optional = true default-features = false [build-dependencies.autocfg] version = "0.1.3" [features] bigint = ["num-bigint"] bigint-std = ["bigint", "num-bigint/std"] default = ["bigint-std", "std"] i128 = ["num-integer/i128", "num-traits/i128"] std = ["num-integer/std", "num-traits/std"] num-rational-0.2.2/Cargo.toml.orig0000644000000032200000000000000124340ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "num-rational" version = "0.2.2" authors = ["The Rust Project Developers"] build = "build.rs" exclude = ["/ci/*", "/.travis.yml", "/bors.toml"] description = "Rational numbers implementation for Rust" homepage = "https://github.com/rust-num/num-rational" documentation = "https://docs.rs/num-rational" readme = "README.md" keywords = ["mathematics", "numerics"] categories = ["algorithms", "data-structures", "science", "no-std"] license = "MIT/Apache-2.0" repository = "https://github.com/rust-num/num-rational" [package.metadata.docs.rs] features = ["std", "bigint-std", "serde"] [dependencies.num-bigint] version = "0.2.0" optional = true default-features = false [dependencies.num-integer] version = "0.1.38" default-features = false [dependencies.num-traits] version = "0.2.7" default-features = false [dependencies.serde] version = "1.0.0" optional = true default-features = false [build-dependencies.autocfg] version = "0.1.3" [features] bigint = ["num-bigint"] bigint-std = ["bigint", "num-bigint/std"] default = ["bigint-std", "std"] i128 = ["num-integer/i128", "num-traits/i128"] std = ["num-integer/std", "num-traits/std"] num-rational-0.2.2/LICENSE-APACHE010066400247370024737000000251371343362654300143350ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. num-rational-0.2.2/LICENSE-MIT010066400247370024737000000020571343362654300140410ustar0000000000000000Copyright (c) 2014 The Rust Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. num-rational-0.2.2/README.md010066400247370024737000000022421343362654300136600ustar0000000000000000# num-rational [![crate](https://img.shields.io/crates/v/num-rational.svg)](https://crates.io/crates/num-rational) [![documentation](https://docs.rs/num-rational/badge.svg)](https://docs.rs/num-rational) ![minimum rustc 1.15](https://img.shields.io/badge/rustc-1.15+-red.svg) [![Travis status](https://travis-ci.org/rust-num/num-rational.svg?branch=master)](https://travis-ci.org/rust-num/num-rational) Generic `Rational` numbers for Rust. ## Usage Add this to your `Cargo.toml`: ```toml [dependencies] num-rational = "0.2" ``` and this to your crate root: ```rust extern crate num_rational; ``` ## Features This crate can be used without the standard library (`#![no_std]`) by disabling the default `std` feature. Use this in `Cargo.toml`: ```toml [dependencies.num-rational] version = "0.2" default-features = false ``` Implementations for `i128` and `u128` are only available with Rust 1.26 and later. The build script automatically detects this, but you can make it mandatory by enabling the `i128` crate feature. ## Releases Release notes are available in [RELEASES.md](RELEASES.md). ## Compatibility The `num-rational` crate is tested for rustc 1.15 and greater. num-rational-0.2.2/RELEASES.md010066400247370024737000000052301347757152700141370ustar0000000000000000# Release 0.2.2 (2019-06-10) - [`Ratio` now implements `Zero::set_zero` and `One::set_one`][47]. **Contributors**: @cuviper, @ignatenkobrain, @vks [47]: https://github.com/rust-num/num-rational/pull/47 # Release 0.2.1 (2018-06-22) - Maintenance release to fix `html_root_url`. # Release 0.2.0 (2018-06-19) ### Enhancements - [`Ratio` now implements `One::is_one` and the `Inv` trait][19]. - [`Ratio` now implements `Sum` and `Product`][25]. - [`Ratio` now supports `i128` and `u128` components][29] with Rust 1.26+. - [`Ratio` now implements the `Pow` trait][21]. ### Breaking Changes - [`num-rational` now requires rustc 1.15 or greater][18]. - [There is now a `std` feature][23], enabled by default, along with the implication that building *without* this feature makes this a `#![no_std]` crate. A few methods now require `FloatCore` instead of `Float`. - [The `serde` dependency has been updated to 1.0][24], and `rustc-serialize` is no longer supported by `num-rational`. - The optional `num-bigint` dependency has been updated to 0.2, and should be enabled using the `bigint-std` feature. In the future, it may be possible to use the `bigint` feature with `no_std`. **Contributors**: @clarcharr, @cuviper, @Emerentius, @robomancer-or, @vks [18]: https://github.com/rust-num/num-rational/pull/18 [19]: https://github.com/rust-num/num-rational/pull/19 [21]: https://github.com/rust-num/num-rational/pull/21 [23]: https://github.com/rust-num/num-rational/pull/23 [24]: https://github.com/rust-num/num-rational/pull/24 [25]: https://github.com/rust-num/num-rational/pull/25 [29]: https://github.com/rust-num/num-rational/pull/29 # Release 0.1.42 (2018-02-08) - Maintenance release to update dependencies. # Release 0.1.41 (2018-01-26) - [num-rational now has its own source repository][num-356] at [rust-num/num-rational][home]. - [`Ratio` now implements `CheckedAdd`, `CheckedSub`, `CheckedMul`, and `CheckedDiv`][11]. - [`Ratio` now implements `AddAssign`, `SubAssign`, `MulAssign`, `DivAssign`, and `RemAssign`][12] with either `Ratio` or an integer on the right side. The non-assignment operators now also accept integers as an operand. - [`Ratio` operators now make fewer `clone()` calls][14]. Thanks to @c410-f3r, @cuviper, and @psimonyi for their contributions! [home]: https://github.com/rust-num/num-rational [num-356]: https://github.com/rust-num/num/pull/356 [11]: https://github.com/rust-num/num-rational/pull/11 [12]: https://github.com/rust-num/num-rational/pull/12 [14]: https://github.com/rust-num/num-rational/pull/14 # Prior releases No prior release notes were kept. Thanks all the same to the many contributors that have made this crate what it is! num-rational-0.2.2/build.rs010066400247370024737000000004651346540350700140510ustar0000000000000000extern crate autocfg; use std::env; fn main() { let ac = autocfg::new(); if ac.probe_type("i128") { println!("cargo:rustc-cfg=has_i128"); } else if env::var_os("CARGO_FEATURE_I128").is_some() { panic!("i128 support was not detected!"); } autocfg::rerun_path(file!()); } num-rational-0.2.2/src/lib.rs010066400247370024737000001704351347757103600143220ustar0000000000000000// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Rational numbers //! //! ## Compatibility //! //! The `num-rational` crate is tested for rustc 1.15 and greater. #![doc(html_root_url = "https://docs.rs/num-rational/0.2")] #![no_std] #[cfg(feature = "bigint")] extern crate num_bigint as bigint; #[cfg(feature = "serde")] extern crate serde; extern crate num_integer as integer; extern crate num_traits as traits; #[cfg(feature = "std")] #[cfg_attr(test, macro_use)] extern crate std; use core::cmp; use core::fmt; use core::hash::{Hash, Hasher}; use core::ops::{Add, Div, Mul, Neg, Rem, Sub}; use core::str::FromStr; #[cfg(feature = "std")] use std::error::Error; #[cfg(feature = "bigint")] use bigint::{BigInt, BigUint, Sign}; use integer::Integer; use traits::float::FloatCore; use traits::{ Bounded, CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, FromPrimitive, Inv, Num, NumCast, One, Pow, Signed, Zero, }; /// Represents the ratio between two numbers. #[derive(Copy, Clone, Debug)] #[allow(missing_docs)] pub struct Ratio { /// Numerator. numer: T, /// Denominator. denom: T, } /// Alias for a `Ratio` of machine-sized integers. pub type Rational = Ratio; /// Alias for a `Ratio` of 32-bit-sized integers. pub type Rational32 = Ratio; /// Alias for a `Ratio` of 64-bit-sized integers. pub type Rational64 = Ratio; #[cfg(feature = "bigint")] /// Alias for arbitrary precision rationals. pub type BigRational = Ratio; impl Ratio { /// Creates a new `Ratio`. Fails if `denom` is zero. #[inline] pub fn new(numer: T, denom: T) -> Ratio { if denom.is_zero() { panic!("denominator == 0"); } let mut ret = Ratio::new_raw(numer, denom); ret.reduce(); ret } /// Creates a `Ratio` representing the integer `t`. #[inline] pub fn from_integer(t: T) -> Ratio { Ratio::new_raw(t, One::one()) } /// Creates a `Ratio` without checking for `denom == 0` or reducing. #[inline] pub fn new_raw(numer: T, denom: T) -> Ratio { Ratio { numer: numer, denom: denom, } } /// Converts to an integer, rounding towards zero. #[inline] pub fn to_integer(&self) -> T { self.trunc().numer } /// Gets an immutable reference to the numerator. #[inline] pub fn numer<'a>(&'a self) -> &'a T { &self.numer } /// Gets an immutable reference to the denominator. #[inline] pub fn denom<'a>(&'a self) -> &'a T { &self.denom } /// Returns true if the rational number is an integer (denominator is 1). #[inline] pub fn is_integer(&self) -> bool { self.denom.is_one() } /// Puts self into lowest terms, with denom > 0. fn reduce(&mut self) { let g: T = self.numer.gcd(&self.denom); // FIXME(#5992): assignment operator overloads // self.numer /= g; // T: Clone + Integer != T: Clone + NumAssign self.numer = self.numer.clone() / g.clone(); // FIXME(#5992): assignment operator overloads // self.denom /= g; // T: Clone + Integer != T: Clone + NumAssign self.denom = self.denom.clone() / g; // keep denom positive! if self.denom < T::zero() { self.numer = T::zero() - self.numer.clone(); self.denom = T::zero() - self.denom.clone(); } } /// Returns a reduced copy of self. /// /// In general, it is not necessary to use this method, as the only /// method of procuring a non-reduced fraction is through `new_raw`. pub fn reduced(&self) -> Ratio { let mut ret = self.clone(); ret.reduce(); ret } /// Returns the reciprocal. /// /// Fails if the `Ratio` is zero. #[inline] pub fn recip(&self) -> Ratio { match self.numer.cmp(&T::zero()) { cmp::Ordering::Equal => panic!("numerator == 0"), cmp::Ordering::Greater => Ratio::new_raw(self.denom.clone(), self.numer.clone()), cmp::Ordering::Less => Ratio::new_raw( T::zero() - self.denom.clone(), T::zero() - self.numer.clone(), ), } } /// Rounds towards minus infinity. #[inline] pub fn floor(&self) -> Ratio { if *self < Zero::zero() { let one: T = One::one(); Ratio::from_integer( (self.numer.clone() - self.denom.clone() + one) / self.denom.clone(), ) } else { Ratio::from_integer(self.numer.clone() / self.denom.clone()) } } /// Rounds towards plus infinity. #[inline] pub fn ceil(&self) -> Ratio { if *self < Zero::zero() { Ratio::from_integer(self.numer.clone() / self.denom.clone()) } else { let one: T = One::one(); Ratio::from_integer( (self.numer.clone() + self.denom.clone() - one) / self.denom.clone(), ) } } /// Rounds to the nearest integer. Rounds half-way cases away from zero. #[inline] pub fn round(&self) -> Ratio { let zero: Ratio = Zero::zero(); let one: T = One::one(); let two: T = one.clone() + one.clone(); // Find unsigned fractional part of rational number let mut fractional = self.fract(); if fractional < zero { fractional = zero - fractional }; // The algorithm compares the unsigned fractional part with 1/2, that // is, a/b >= 1/2, or a >= b/2. For odd denominators, we use // a >= (b/2)+1. This avoids overflow issues. let half_or_larger = if fractional.denom().is_even() { *fractional.numer() >= fractional.denom().clone() / two.clone() } else { *fractional.numer() >= (fractional.denom().clone() / two.clone()) + one.clone() }; if half_or_larger { let one: Ratio = One::one(); if *self >= Zero::zero() { self.trunc() + one } else { self.trunc() - one } } else { self.trunc() } } /// Rounds towards zero. #[inline] pub fn trunc(&self) -> Ratio { Ratio::from_integer(self.numer.clone() / self.denom.clone()) } /// Returns the fractional part of a number, with division rounded towards zero. /// /// Satisfies `self == self.trunc() + self.fract()`. #[inline] pub fn fract(&self) -> Ratio { Ratio::new_raw(self.numer.clone() % self.denom.clone(), self.denom.clone()) } } impl> Ratio { /// Raises the `Ratio` to the power of an exponent. #[inline] pub fn pow(&self, expon: i32) -> Ratio { Pow::pow(self, expon) } } macro_rules! pow_impl { ($exp:ty) => { pow_impl!($exp, $exp); }; ($exp:ty, $unsigned:ty) => { impl> Pow<$exp> for Ratio { type Output = Ratio; #[inline] fn pow(self, expon: $exp) -> Ratio { match expon.cmp(&0) { cmp::Ordering::Equal => One::one(), cmp::Ordering::Less => { let expon = expon.wrapping_abs() as $unsigned; Ratio::new_raw(Pow::pow(self.denom, expon), Pow::pow(self.numer, expon)) } cmp::Ordering::Greater => Ratio::new_raw( Pow::pow(self.numer, expon as $unsigned), Pow::pow(self.denom, expon as $unsigned), ), } } } impl<'a, T: Clone + Integer + Pow<$unsigned, Output = T>> Pow<$exp> for &'a Ratio { type Output = Ratio; #[inline] fn pow(self, expon: $exp) -> Ratio { Pow::pow(self.clone(), expon) } } impl<'a, T: Clone + Integer + Pow<$unsigned, Output = T>> Pow<&'a $exp> for Ratio { type Output = Ratio; #[inline] fn pow(self, expon: &'a $exp) -> Ratio { Pow::pow(self, *expon) } } impl<'a, 'b, T: Clone + Integer + Pow<$unsigned, Output = T>> Pow<&'a $exp> for &'b Ratio { type Output = Ratio; #[inline] fn pow(self, expon: &'a $exp) -> Ratio { Pow::pow(self.clone(), *expon) } } }; } // this is solely to make `pow_impl!` work trait WrappingAbs: Sized { fn wrapping_abs(self) -> Self { self } } impl WrappingAbs for u8 {} impl WrappingAbs for u16 {} impl WrappingAbs for u32 {} impl WrappingAbs for u64 {} impl WrappingAbs for usize {} pow_impl!(i8, u8); pow_impl!(i16, u16); pow_impl!(i32, u32); pow_impl!(i64, u64); pow_impl!(isize, usize); pow_impl!(u8); pow_impl!(u16); pow_impl!(u32); pow_impl!(u64); pow_impl!(usize); // TODO: pow_impl!(BigUint) and pow_impl!(BigInt, BigUint) #[cfg(feature = "bigint")] impl Ratio { /// Converts a float into a rational number. pub fn from_float(f: T) -> Option { if !f.is_finite() { return None; } let (mantissa, exponent, sign) = f.integer_decode(); let bigint_sign = if sign == 1 { Sign::Plus } else { Sign::Minus }; if exponent < 0 { let one: BigInt = One::one(); let denom: BigInt = one << ((-exponent) as usize); let numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap(); Some(Ratio::new(BigInt::from_biguint(bigint_sign, numer), denom)) } else { let mut numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap(); numer = numer << (exponent as usize); Some(Ratio::from_integer(BigInt::from_biguint( bigint_sign, numer, ))) } } } // From integer impl From for Ratio where T: Clone + Integer, { fn from(x: T) -> Ratio { Ratio::from_integer(x) } } // From pair (through the `new` constructor) impl From<(T, T)> for Ratio where T: Clone + Integer, { fn from(pair: (T, T)) -> Ratio { Ratio::new(pair.0, pair.1) } } // Comparisons // Mathematically, comparing a/b and c/d is the same as comparing a*d and b*c, but it's very easy // for those multiplications to overflow fixed-size integers, so we need to take care. impl Ord for Ratio { #[inline] fn cmp(&self, other: &Self) -> cmp::Ordering { // With equal denominators, the numerators can be directly compared if self.denom == other.denom { let ord = self.numer.cmp(&other.numer); return if self.denom < T::zero() { ord.reverse() } else { ord }; } // With equal numerators, the denominators can be inversely compared if self.numer == other.numer { let ord = self.denom.cmp(&other.denom); return if self.numer < T::zero() { ord } else { ord.reverse() }; } // Unfortunately, we don't have CheckedMul to try. That could sometimes avoid all the // division below, or even always avoid it for BigInt and BigUint. // FIXME- future breaking change to add Checked* to Integer? // Compare as floored integers and remainders let (self_int, self_rem) = self.numer.div_mod_floor(&self.denom); let (other_int, other_rem) = other.numer.div_mod_floor(&other.denom); match self_int.cmp(&other_int) { cmp::Ordering::Greater => cmp::Ordering::Greater, cmp::Ordering::Less => cmp::Ordering::Less, cmp::Ordering::Equal => { match (self_rem.is_zero(), other_rem.is_zero()) { (true, true) => cmp::Ordering::Equal, (true, false) => cmp::Ordering::Less, (false, true) => cmp::Ordering::Greater, (false, false) => { // Compare the reciprocals of the remaining fractions in reverse let self_recip = Ratio::new_raw(self.denom.clone(), self_rem); let other_recip = Ratio::new_raw(other.denom.clone(), other_rem); self_recip.cmp(&other_recip).reverse() } } } } } } impl PartialOrd for Ratio { #[inline] fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl PartialEq for Ratio { #[inline] fn eq(&self, other: &Self) -> bool { self.cmp(other) == cmp::Ordering::Equal } } impl Eq for Ratio {} // NB: We can't just `#[derive(Hash)]`, because it needs to agree // with `Eq` even for non-reduced ratios. impl Hash for Ratio { fn hash(&self, state: &mut H) { recurse(&self.numer, &self.denom, state); fn recurse(numer: &T, denom: &T, state: &mut H) { if !denom.is_zero() { let (int, rem) = numer.div_mod_floor(denom); int.hash(state); recurse(denom, &rem, state); } else { denom.hash(state); } } } } mod iter_sum_product { use core::iter::{Product, Sum}; use integer::Integer; use traits::{One, Zero}; use Ratio; impl Sum for Ratio { fn sum(iter: I) -> Self where I: Iterator>, { iter.fold(Self::zero(), |sum, num| sum + num) } } impl<'a, T: Integer + Clone> Sum<&'a Ratio> for Ratio { fn sum(iter: I) -> Self where I: Iterator>, { iter.fold(Self::zero(), |sum, num| sum + num) } } impl Product for Ratio { fn product(iter: I) -> Self where I: Iterator>, { iter.fold(Self::one(), |prod, num| prod * num) } } impl<'a, T: Integer + Clone> Product<&'a Ratio> for Ratio { fn product(iter: I) -> Self where I: Iterator>, { iter.fold(Self::one(), |prod, num| prod * num) } } } mod opassign { use core::ops::{AddAssign, DivAssign, MulAssign, RemAssign, SubAssign}; use integer::Integer; use traits::NumAssign; use Ratio; impl AddAssign for Ratio { fn add_assign(&mut self, other: Ratio) { self.numer *= other.denom.clone(); self.numer += self.denom.clone() * other.numer; self.denom *= other.denom; self.reduce(); } } impl DivAssign for Ratio { fn div_assign(&mut self, other: Ratio) { self.numer *= other.denom; self.denom *= other.numer; self.reduce(); } } impl MulAssign for Ratio { fn mul_assign(&mut self, other: Ratio) { self.numer *= other.numer; self.denom *= other.denom; self.reduce(); } } impl RemAssign for Ratio { fn rem_assign(&mut self, other: Ratio) { self.numer *= other.denom.clone(); self.numer %= self.denom.clone() * other.numer; self.denom *= other.denom; self.reduce(); } } impl SubAssign for Ratio { fn sub_assign(&mut self, other: Ratio) { self.numer *= other.denom.clone(); self.numer -= self.denom.clone() * other.numer; self.denom *= other.denom; self.reduce(); } } // a/b + c/1 = (a*1 + b*c) / (b*1) = (a + b*c) / b impl AddAssign for Ratio { fn add_assign(&mut self, other: T) { self.numer += self.denom.clone() * other; self.reduce(); } } impl DivAssign for Ratio { fn div_assign(&mut self, other: T) { self.denom *= other; self.reduce(); } } impl MulAssign for Ratio { fn mul_assign(&mut self, other: T) { self.numer *= other; self.reduce(); } } // a/b % c/1 = (a*1 % b*c) / (b*1) = (a % b*c) / b impl RemAssign for Ratio { fn rem_assign(&mut self, other: T) { self.numer %= self.denom.clone() * other; self.reduce(); } } // a/b - c/1 = (a*1 - b*c) / (b*1) = (a - b*c) / b impl SubAssign for Ratio { fn sub_assign(&mut self, other: T) { self.numer -= self.denom.clone() * other; self.reduce(); } } macro_rules! forward_op_assign { (impl $imp:ident, $method:ident) => { impl<'a, T: Clone + Integer + NumAssign> $imp<&'a Ratio> for Ratio { #[inline] fn $method(&mut self, other: &Ratio) { self.$method(other.clone()) } } impl<'a, T: Clone + Integer + NumAssign> $imp<&'a T> for Ratio { #[inline] fn $method(&mut self, other: &T) { self.$method(other.clone()) } } }; } forward_op_assign!(impl AddAssign, add_assign); forward_op_assign!(impl DivAssign, div_assign); forward_op_assign!(impl MulAssign, mul_assign); forward_op_assign!(impl RemAssign, rem_assign); forward_op_assign!(impl SubAssign, sub_assign); } macro_rules! forward_ref_ref_binop { (impl $imp:ident, $method:ident) => { impl<'a, 'b, T: Clone + Integer> $imp<&'b Ratio> for &'a Ratio { type Output = Ratio; #[inline] fn $method(self, other: &'b Ratio) -> Ratio { self.clone().$method(other.clone()) } } impl<'a, 'b, T: Clone + Integer> $imp<&'b T> for &'a Ratio { type Output = Ratio; #[inline] fn $method(self, other: &'b T) -> Ratio { self.clone().$method(other.clone()) } } }; } macro_rules! forward_ref_val_binop { (impl $imp:ident, $method:ident) => { impl<'a, T> $imp> for &'a Ratio where T: Clone + Integer, { type Output = Ratio; #[inline] fn $method(self, other: Ratio) -> Ratio { self.clone().$method(other) } } impl<'a, T> $imp for &'a Ratio where T: Clone + Integer, { type Output = Ratio; #[inline] fn $method(self, other: T) -> Ratio { self.clone().$method(other) } } }; } macro_rules! forward_val_ref_binop { (impl $imp:ident, $method:ident) => { impl<'a, T> $imp<&'a Ratio> for Ratio where T: Clone + Integer, { type Output = Ratio; #[inline] fn $method(self, other: &Ratio) -> Ratio { self.$method(other.clone()) } } impl<'a, T> $imp<&'a T> for Ratio where T: Clone + Integer, { type Output = Ratio; #[inline] fn $method(self, other: &T) -> Ratio { self.$method(other.clone()) } } }; } macro_rules! forward_all_binop { (impl $imp:ident, $method:ident) => { forward_ref_ref_binop!(impl $imp, $method); forward_ref_val_binop!(impl $imp, $method); forward_val_ref_binop!(impl $imp, $method); }; } // Arithmetic forward_all_binop!(impl Mul, mul); // a/b * c/d = (a*c)/(b*d) impl Mul> for Ratio where T: Clone + Integer, { type Output = Ratio; #[inline] fn mul(self, rhs: Ratio) -> Ratio { Ratio::new(self.numer * rhs.numer, self.denom * rhs.denom) } } // a/b * c/1 = (a*c) / (b*1) = (a*c) / b impl Mul for Ratio where T: Clone + Integer, { type Output = Ratio; #[inline] fn mul(self, rhs: T) -> Ratio { Ratio::new(self.numer * rhs, self.denom) } } forward_all_binop!(impl Div, div); // (a/b) / (c/d) = (a*d) / (b*c) impl Div> for Ratio where T: Clone + Integer, { type Output = Ratio; #[inline] fn div(self, rhs: Ratio) -> Ratio { Ratio::new(self.numer * rhs.denom, self.denom * rhs.numer) } } // (a/b) / (c/1) = (a*1) / (b*c) = a / (b*c) impl Div for Ratio where T: Clone + Integer, { type Output = Ratio; #[inline] fn div(self, rhs: T) -> Ratio { Ratio::new(self.numer, self.denom * rhs) } } macro_rules! arith_impl { (impl $imp:ident, $method:ident) => { forward_all_binop!(impl $imp, $method); // Abstracts the a/b `op` c/d = (a*d `op` b*c) / (b*d) pattern impl $imp> for Ratio { type Output = Ratio; #[inline] fn $method(self, rhs: Ratio) -> Ratio { Ratio::new( (self.numer * rhs.denom.clone()).$method(self.denom.clone() * rhs.numer), self.denom * rhs.denom, ) } } // Abstracts the a/b `op` c/1 = (a*1 `op` b*c) / (b*1) = (a `op` b*c) / b pattern impl $imp for Ratio { type Output = Ratio; #[inline] fn $method(self, rhs: T) -> Ratio { Ratio::new(self.numer.$method(self.denom.clone() * rhs), self.denom) } } }; } arith_impl!(impl Add, add); arith_impl!(impl Sub, sub); arith_impl!(impl Rem, rem); // Like `std::try!` for Option, unwrap the value or early-return None. // Since Rust 1.22 this can be replaced by the `?` operator. macro_rules! otry { ($expr:expr) => { match $expr { Some(val) => val, None => return None, } }; } // a/b * c/d = (a*c)/(b*d) impl CheckedMul for Ratio where T: Clone + Integer + CheckedMul, { #[inline] fn checked_mul(&self, rhs: &Ratio) -> Option> { Some(Ratio::new( otry!(self.numer.checked_mul(&rhs.numer)), otry!(self.denom.checked_mul(&rhs.denom)), )) } } // (a/b) / (c/d) = (a*d)/(b*c) impl CheckedDiv for Ratio where T: Clone + Integer + CheckedMul, { #[inline] fn checked_div(&self, rhs: &Ratio) -> Option> { let bc = otry!(self.denom.checked_mul(&rhs.numer)); if bc.is_zero() { None } else { Some(Ratio::new(otry!(self.numer.checked_mul(&rhs.denom)), bc)) } } } // As arith_impl! but for Checked{Add,Sub} traits macro_rules! checked_arith_impl { (impl $imp:ident, $method:ident) => { impl $imp for Ratio { #[inline] fn $method(&self, rhs: &Ratio) -> Option> { let ad = otry!(self.numer.checked_mul(&rhs.denom)); let bc = otry!(self.denom.checked_mul(&rhs.numer)); let bd = otry!(self.denom.checked_mul(&rhs.denom)); Some(Ratio::new(otry!(ad.$method(&bc)), bd)) } } }; } // a/b + c/d = (a*d + b*c)/(b*d) checked_arith_impl!(impl CheckedAdd, checked_add); // a/b - c/d = (a*d - b*c)/(b*d) checked_arith_impl!(impl CheckedSub, checked_sub); impl Neg for Ratio where T: Clone + Integer + Neg, { type Output = Ratio; #[inline] fn neg(self) -> Ratio { Ratio::new_raw(-self.numer, self.denom) } } impl<'a, T> Neg for &'a Ratio where T: Clone + Integer + Neg, { type Output = Ratio; #[inline] fn neg(self) -> Ratio { -self.clone() } } impl Inv for Ratio where T: Clone + Integer, { type Output = Ratio; #[inline] fn inv(self) -> Ratio { self.recip() } } impl<'a, T> Inv for &'a Ratio where T: Clone + Integer, { type Output = Ratio; #[inline] fn inv(self) -> Ratio { self.recip() } } // Constants impl Zero for Ratio { #[inline] fn zero() -> Ratio { Ratio::new_raw(Zero::zero(), One::one()) } #[inline] fn is_zero(&self) -> bool { self.numer.is_zero() } #[inline] fn set_zero(&mut self) { self.numer.set_zero(); self.denom.set_one(); } } impl One for Ratio { #[inline] fn one() -> Ratio { Ratio::new_raw(One::one(), One::one()) } #[inline] fn is_one(&self) -> bool { self.numer == self.denom } #[inline] fn set_one(&mut self) { self.numer.set_one(); self.denom.set_one(); } } impl Num for Ratio { type FromStrRadixErr = ParseRatioError; /// Parses `numer/denom` where the numbers are in base `radix`. fn from_str_radix(s: &str, radix: u32) -> Result, ParseRatioError> { if s.splitn(2, '/').count() == 2 { let mut parts = s.splitn(2, '/').map(|ss| { T::from_str_radix(ss, radix).map_err(|_| ParseRatioError { kind: RatioErrorKind::ParseError, }) }); let numer: T = parts.next().unwrap()?; let denom: T = parts.next().unwrap()?; if denom.is_zero() { Err(ParseRatioError { kind: RatioErrorKind::ZeroDenominator, }) } else { Ok(Ratio::new(numer, denom)) } } else { Err(ParseRatioError { kind: RatioErrorKind::ParseError, }) } } } impl Signed for Ratio { #[inline] fn abs(&self) -> Ratio { if self.is_negative() { -self.clone() } else { self.clone() } } #[inline] fn abs_sub(&self, other: &Ratio) -> Ratio { if *self <= *other { Zero::zero() } else { self - other } } #[inline] fn signum(&self) -> Ratio { if self.is_positive() { Self::one() } else if self.is_zero() { Self::zero() } else { -Self::one() } } #[inline] fn is_positive(&self) -> bool { (self.numer.is_positive() && self.denom.is_positive()) || (self.numer.is_negative() && self.denom.is_negative()) } #[inline] fn is_negative(&self) -> bool { (self.numer.is_negative() && self.denom.is_positive()) || (self.numer.is_positive() && self.denom.is_negative()) } } // String conversions impl fmt::Display for Ratio where T: fmt::Display + Eq + One, { /// Renders as `numer/denom`. If denom=1, renders as numer. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.denom.is_one() { write!(f, "{}", self.numer) } else { write!(f, "{}/{}", self.numer, self.denom) } } } impl FromStr for Ratio { type Err = ParseRatioError; /// Parses `numer/denom` or just `numer`. fn from_str(s: &str) -> Result, ParseRatioError> { let mut split = s.splitn(2, '/'); let n = try!(split.next().ok_or(ParseRatioError { kind: RatioErrorKind::ParseError })); let num = try!(FromStr::from_str(n).map_err(|_| ParseRatioError { kind: RatioErrorKind::ParseError })); let d = split.next().unwrap_or("1"); let den = try!(FromStr::from_str(d).map_err(|_| ParseRatioError { kind: RatioErrorKind::ParseError })); if Zero::is_zero(&den) { Err(ParseRatioError { kind: RatioErrorKind::ZeroDenominator, }) } else { Ok(Ratio::new(num, den)) } } } impl Into<(T, T)> for Ratio { fn into(self) -> (T, T) { (self.numer, self.denom) } } #[cfg(feature = "serde")] impl serde::Serialize for Ratio where T: serde::Serialize + Clone + Integer + PartialOrd, { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { (self.numer(), self.denom()).serialize(serializer) } } #[cfg(feature = "serde")] impl<'de, T> serde::Deserialize<'de> for Ratio where T: serde::Deserialize<'de> + Clone + Integer + PartialOrd, { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { use serde::de::Error; use serde::de::Unexpected; let (numer, denom): (T, T) = try!(serde::Deserialize::deserialize(deserializer)); if denom.is_zero() { Err(Error::invalid_value( Unexpected::Signed(0), &"a ratio with non-zero denominator", )) } else { Ok(Ratio::new_raw(numer, denom)) } } } // FIXME: Bubble up specific errors #[derive(Copy, Clone, Debug, PartialEq)] pub struct ParseRatioError { kind: RatioErrorKind, } #[derive(Copy, Clone, Debug, PartialEq)] enum RatioErrorKind { ParseError, ZeroDenominator, } impl fmt::Display for ParseRatioError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.kind.description().fmt(f) } } #[cfg(feature = "std")] impl Error for ParseRatioError { fn description(&self) -> &str { self.kind.description() } } impl RatioErrorKind { fn description(&self) -> &'static str { match *self { RatioErrorKind::ParseError => "failed to parse integer", RatioErrorKind::ZeroDenominator => "zero value denominator", } } } #[cfg(feature = "bigint")] impl FromPrimitive for Ratio { fn from_i64(n: i64) -> Option { Some(Ratio::from_integer(n.into())) } #[cfg(has_i128)] fn from_i128(n: i128) -> Option { Some(Ratio::from_integer(n.into())) } fn from_u64(n: u64) -> Option { Some(Ratio::from_integer(n.into())) } #[cfg(has_i128)] fn from_u128(n: u128) -> Option { Some(Ratio::from_integer(n.into())) } fn from_f32(n: f32) -> Option { Ratio::from_float(n) } fn from_f64(n: f64) -> Option { Ratio::from_float(n) } } macro_rules! from_primitive_integer { ($typ:ty, $approx:ident) => { impl FromPrimitive for Ratio<$typ> { fn from_i64(n: i64) -> Option { <$typ as FromPrimitive>::from_i64(n).map(Ratio::from_integer) } #[cfg(has_i128)] fn from_i128(n: i128) -> Option { <$typ as FromPrimitive>::from_i128(n).map(Ratio::from_integer) } fn from_u64(n: u64) -> Option { <$typ as FromPrimitive>::from_u64(n).map(Ratio::from_integer) } #[cfg(has_i128)] fn from_u128(n: u128) -> Option { <$typ as FromPrimitive>::from_u128(n).map(Ratio::from_integer) } fn from_f32(n: f32) -> Option { $approx(n, 10e-20, 30) } fn from_f64(n: f64) -> Option { $approx(n, 10e-20, 30) } } }; } from_primitive_integer!(i8, approximate_float); from_primitive_integer!(i16, approximate_float); from_primitive_integer!(i32, approximate_float); from_primitive_integer!(i64, approximate_float); #[cfg(has_i128)] from_primitive_integer!(i128, approximate_float); from_primitive_integer!(isize, approximate_float); from_primitive_integer!(u8, approximate_float_unsigned); from_primitive_integer!(u16, approximate_float_unsigned); from_primitive_integer!(u32, approximate_float_unsigned); from_primitive_integer!(u64, approximate_float_unsigned); #[cfg(has_i128)] from_primitive_integer!(u128, approximate_float_unsigned); from_primitive_integer!(usize, approximate_float_unsigned); impl Ratio { pub fn approximate_float(f: F) -> Option> { // 1/10e-20 < 1/2**32 which seems like a good default, and 30 seems // to work well. Might want to choose something based on the types in the future, e.g. // T::max().recip() and T::bits() or something similar. let epsilon = ::from(10e-20).expect("Can't convert 10e-20"); approximate_float(f, epsilon, 30) } } fn approximate_float(val: F, max_error: F, max_iterations: usize) -> Option> where T: Integer + Signed + Bounded + NumCast + Clone, F: FloatCore + NumCast, { let negative = val.is_sign_negative(); let abs_val = val.abs(); let r = approximate_float_unsigned(abs_val, max_error, max_iterations); // Make negative again if needed if negative { r.map(|r| r.neg()) } else { r } } // No Unsigned constraint because this also works on positive integers and is called // like that, see above fn approximate_float_unsigned(val: F, max_error: F, max_iterations: usize) -> Option> where T: Integer + Bounded + NumCast + Clone, F: FloatCore + NumCast, { // Continued fractions algorithm // http://mathforum.org/dr.math/faq/faq.fractions.html#decfrac if val < F::zero() || val.is_nan() { return None; } let mut q = val; let mut n0 = T::zero(); let mut d0 = T::one(); let mut n1 = T::one(); let mut d1 = T::zero(); let t_max = T::max_value(); let t_max_f = match ::from(t_max.clone()) { None => return None, Some(t_max_f) => t_max_f, }; // 1/epsilon > T::MAX let epsilon = t_max_f.recip(); // Overflow if q > t_max_f { return None; } for _ in 0..max_iterations { let a = match ::from(q) { None => break, Some(a) => a, }; let a_f = match ::from(a.clone()) { None => break, Some(a_f) => a_f, }; let f = q - a_f; // Prevent overflow if !a.is_zero() && (n1 > t_max.clone() / a.clone() || d1 > t_max.clone() / a.clone() || a.clone() * n1.clone() > t_max.clone() - n0.clone() || a.clone() * d1.clone() > t_max.clone() - d0.clone()) { break; } let n = a.clone() * n1.clone() + n0.clone(); let d = a.clone() * d1.clone() + d0.clone(); n0 = n1; d0 = d1; n1 = n.clone(); d1 = d.clone(); // Simplify fraction. Doing so here instead of at the end // allows us to get closer to the target value without overflows let g = Integer::gcd(&n1, &d1); if !g.is_zero() { n1 = n1 / g.clone(); d1 = d1 / g.clone(); } // Close enough? let (n_f, d_f) = match (::from(n), ::from(d)) { (Some(n_f), Some(d_f)) => (n_f, d_f), _ => break, }; if (n_f / d_f - val).abs() < max_error { break; } // Prevent division by ~0 if f < epsilon { break; } q = f.recip(); } // Overflow if d1.is_zero() { return None; } Some(Ratio::new(n1, d1)) } #[cfg(test)] #[cfg(feature = "std")] fn hash(x: &T) -> u64 { use std::collections::hash_map::RandomState; use std::hash::BuildHasher; let mut hasher = ::Hasher::new(); x.hash(&mut hasher); hasher.finish() } #[cfg(test)] mod test { #[cfg(feature = "bigint")] use super::BigRational; use super::{Ratio, Rational, Rational64}; use core::f64; use core::i32; use core::str::FromStr; use integer::Integer; use traits::{FromPrimitive, One, Pow, Signed, Zero}; pub const _0: Rational = Ratio { numer: 0, denom: 1 }; pub const _1: Rational = Ratio { numer: 1, denom: 1 }; pub const _2: Rational = Ratio { numer: 2, denom: 1 }; pub const _NEG2: Rational = Ratio { numer: -2, denom: 1, }; pub const _1_2: Rational = Ratio { numer: 1, denom: 2 }; pub const _3_2: Rational = Ratio { numer: 3, denom: 2 }; pub const _NEG1_2: Rational = Ratio { numer: -1, denom: 2, }; pub const _1_NEG2: Rational = Ratio { numer: 1, denom: -2, }; pub const _NEG1_NEG2: Rational = Ratio { numer: -1, denom: -2, }; pub const _1_3: Rational = Ratio { numer: 1, denom: 3 }; pub const _NEG1_3: Rational = Ratio { numer: -1, denom: 3, }; pub const _2_3: Rational = Ratio { numer: 2, denom: 3 }; pub const _NEG2_3: Rational = Ratio { numer: -2, denom: 3, }; #[cfg(feature = "bigint")] pub fn to_big(n: Rational) -> BigRational { Ratio::new( FromPrimitive::from_isize(n.numer).unwrap(), FromPrimitive::from_isize(n.denom).unwrap(), ) } #[cfg(not(feature = "bigint"))] pub fn to_big(n: Rational) -> Rational { Ratio::new( FromPrimitive::from_isize(n.numer).unwrap(), FromPrimitive::from_isize(n.denom).unwrap(), ) } #[test] fn test_test_constants() { // check our constants are what Ratio::new etc. would make. assert_eq!(_0, Zero::zero()); assert_eq!(_1, One::one()); assert_eq!(_2, Ratio::from_integer(2)); assert_eq!(_1_2, Ratio::new(1, 2)); assert_eq!(_3_2, Ratio::new(3, 2)); assert_eq!(_NEG1_2, Ratio::new(-1, 2)); assert_eq!(_2, From::from(2)); } #[test] fn test_new_reduce() { let one22 = Ratio::new(2, 2); assert_eq!(one22, One::one()); } #[test] #[should_panic] fn test_new_zero() { let _a = Ratio::new(1, 0); } #[test] fn test_approximate_float() { assert_eq!(Ratio::from_f32(0.5f32), Some(Ratio::new(1i64, 2))); assert_eq!(Ratio::from_f64(0.5f64), Some(Ratio::new(1i32, 2))); assert_eq!(Ratio::from_f32(5f32), Some(Ratio::new(5i64, 1))); assert_eq!(Ratio::from_f64(5f64), Some(Ratio::new(5i32, 1))); assert_eq!(Ratio::from_f32(29.97f32), Some(Ratio::new(2997i64, 100))); assert_eq!(Ratio::from_f32(-29.97f32), Some(Ratio::new(-2997i64, 100))); assert_eq!(Ratio::::from_f32(63.5f32), Some(Ratio::new(127i8, 2))); assert_eq!(Ratio::::from_f32(126.5f32), Some(Ratio::new(126i8, 1))); assert_eq!(Ratio::::from_f32(127.0f32), Some(Ratio::new(127i8, 1))); assert_eq!(Ratio::::from_f32(127.5f32), None); assert_eq!(Ratio::::from_f32(-63.5f32), Some(Ratio::new(-127i8, 2))); assert_eq!( Ratio::::from_f32(-126.5f32), Some(Ratio::new(-126i8, 1)) ); assert_eq!( Ratio::::from_f32(-127.0f32), Some(Ratio::new(-127i8, 1)) ); assert_eq!(Ratio::::from_f32(-127.5f32), None); assert_eq!(Ratio::::from_f32(-127f32), None); assert_eq!(Ratio::::from_f32(127f32), Some(Ratio::new(127u8, 1))); assert_eq!(Ratio::::from_f32(127.5f32), Some(Ratio::new(255u8, 2))); assert_eq!(Ratio::::from_f32(256f32), None); assert_eq!(Ratio::::from_f64(-10e200), None); assert_eq!(Ratio::::from_f64(10e200), None); assert_eq!(Ratio::::from_f64(f64::INFINITY), None); assert_eq!(Ratio::::from_f64(f64::NEG_INFINITY), None); assert_eq!(Ratio::::from_f64(f64::NAN), None); assert_eq!( Ratio::::from_f64(f64::EPSILON), Some(Ratio::new(1, 4503599627370496)) ); assert_eq!(Ratio::::from_f64(0.0), Some(Ratio::new(0, 1))); assert_eq!(Ratio::::from_f64(-0.0), Some(Ratio::new(0, 1))); } #[test] fn test_cmp() { assert!(_0 == _0 && _1 == _1); assert!(_0 != _1 && _1 != _0); assert!(_0 < _1 && !(_1 < _0)); assert!(_1 > _0 && !(_0 > _1)); assert!(_0 <= _0 && _1 <= _1); assert!(_0 <= _1 && !(_1 <= _0)); assert!(_0 >= _0 && _1 >= _1); assert!(_1 >= _0 && !(_0 >= _1)); } #[test] fn test_cmp_overflow() { use core::cmp::Ordering; // issue #7 example: let big = Ratio::new(128u8, 1); let small = big.recip(); assert!(big > small); // try a few that are closer together // (some matching numer, some matching denom, some neither) let ratios = [ Ratio::new(125_i8, 127_i8), Ratio::new(63_i8, 64_i8), Ratio::new(124_i8, 125_i8), Ratio::new(125_i8, 126_i8), Ratio::new(126_i8, 127_i8), Ratio::new(127_i8, 126_i8), ]; fn check_cmp(a: Ratio, b: Ratio, ord: Ordering) { #[cfg(feature = "std")] println!("comparing {} and {}", a, b); assert_eq!(a.cmp(&b), ord); assert_eq!(b.cmp(&a), ord.reverse()); } for (i, &a) in ratios.iter().enumerate() { check_cmp(a, a, Ordering::Equal); check_cmp(-a, a, Ordering::Less); for &b in &ratios[i + 1..] { check_cmp(a, b, Ordering::Less); check_cmp(-a, -b, Ordering::Greater); check_cmp(a.recip(), b.recip(), Ordering::Greater); check_cmp(-a.recip(), -b.recip(), Ordering::Less); } } } #[test] fn test_to_integer() { assert_eq!(_0.to_integer(), 0); assert_eq!(_1.to_integer(), 1); assert_eq!(_2.to_integer(), 2); assert_eq!(_1_2.to_integer(), 0); assert_eq!(_3_2.to_integer(), 1); assert_eq!(_NEG1_2.to_integer(), 0); } #[test] fn test_numer() { assert_eq!(_0.numer(), &0); assert_eq!(_1.numer(), &1); assert_eq!(_2.numer(), &2); assert_eq!(_1_2.numer(), &1); assert_eq!(_3_2.numer(), &3); assert_eq!(_NEG1_2.numer(), &(-1)); } #[test] fn test_denom() { assert_eq!(_0.denom(), &1); assert_eq!(_1.denom(), &1); assert_eq!(_2.denom(), &1); assert_eq!(_1_2.denom(), &2); assert_eq!(_3_2.denom(), &2); assert_eq!(_NEG1_2.denom(), &2); } #[test] fn test_is_integer() { assert!(_0.is_integer()); assert!(_1.is_integer()); assert!(_2.is_integer()); assert!(!_1_2.is_integer()); assert!(!_3_2.is_integer()); assert!(!_NEG1_2.is_integer()); } #[test] #[cfg(feature = "std")] fn test_show() { use std::string::ToString; assert_eq!(format!("{}", _2), "2".to_string()); assert_eq!(format!("{}", _1_2), "1/2".to_string()); assert_eq!(format!("{}", _0), "0".to_string()); assert_eq!(format!("{}", Ratio::from_integer(-2)), "-2".to_string()); } mod arith { use super::super::{Ratio, Rational}; use super::{to_big, _0, _1, _1_2, _2, _3_2, _NEG1_2}; use traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub}; #[test] fn test_add() { fn test(a: Rational, b: Rational, c: Rational) { assert_eq!(a + b, c); assert_eq!( { let mut x = a; x += b; x }, c ); assert_eq!(to_big(a) + to_big(b), to_big(c)); assert_eq!(a.checked_add(&b), Some(c)); assert_eq!(to_big(a).checked_add(&to_big(b)), Some(to_big(c))); } fn test_assign(a: Rational, b: isize, c: Rational) { assert_eq!(a + b, c); assert_eq!( { let mut x = a; x += b; x }, c ); } test(_1, _1_2, _3_2); test(_1, _1, _2); test(_1_2, _3_2, _2); test(_1_2, _NEG1_2, _0); test_assign(_1_2, 1, _3_2); } #[test] fn test_sub() { fn test(a: Rational, b: Rational, c: Rational) { assert_eq!(a - b, c); assert_eq!( { let mut x = a; x -= b; x }, c ); assert_eq!(to_big(a) - to_big(b), to_big(c)); assert_eq!(a.checked_sub(&b), Some(c)); assert_eq!(to_big(a).checked_sub(&to_big(b)), Some(to_big(c))); } fn test_assign(a: Rational, b: isize, c: Rational) { assert_eq!(a - b, c); assert_eq!( { let mut x = a; x -= b; x }, c ); } test(_1, _1_2, _1_2); test(_3_2, _1_2, _1); test(_1, _NEG1_2, _3_2); test_assign(_1_2, 1, _NEG1_2); } #[test] fn test_mul() { fn test(a: Rational, b: Rational, c: Rational) { assert_eq!(a * b, c); assert_eq!( { let mut x = a; x *= b; x }, c ); assert_eq!(to_big(a) * to_big(b), to_big(c)); assert_eq!(a.checked_mul(&b), Some(c)); assert_eq!(to_big(a).checked_mul(&to_big(b)), Some(to_big(c))); } fn test_assign(a: Rational, b: isize, c: Rational) { assert_eq!(a * b, c); assert_eq!( { let mut x = a; x *= b; x }, c ); } test(_1, _1_2, _1_2); test(_1_2, _3_2, Ratio::new(3, 4)); test(_1_2, _NEG1_2, Ratio::new(-1, 4)); test_assign(_1_2, 2, _1); } #[test] fn test_div() { fn test(a: Rational, b: Rational, c: Rational) { assert_eq!(a / b, c); assert_eq!( { let mut x = a; x /= b; x }, c ); assert_eq!(to_big(a) / to_big(b), to_big(c)); assert_eq!(a.checked_div(&b), Some(c)); assert_eq!(to_big(a).checked_div(&to_big(b)), Some(to_big(c))); } fn test_assign(a: Rational, b: isize, c: Rational) { assert_eq!(a / b, c); assert_eq!( { let mut x = a; x /= b; x }, c ); } test(_1, _1_2, _2); test(_3_2, _1_2, _1 + _2); test(_1, _NEG1_2, _NEG1_2 + _NEG1_2 + _NEG1_2 + _NEG1_2); test_assign(_1, 2, _1_2); } #[test] fn test_rem() { fn test(a: Rational, b: Rational, c: Rational) { assert_eq!(a % b, c); assert_eq!( { let mut x = a; x %= b; x }, c ); assert_eq!(to_big(a) % to_big(b), to_big(c)) } fn test_assign(a: Rational, b: isize, c: Rational) { assert_eq!(a % b, c); assert_eq!( { let mut x = a; x %= b; x }, c ); } test(_3_2, _1, _1_2); test(_2, _NEG1_2, _0); test(_1_2, _2, _1_2); test_assign(_3_2, 1, _1_2); } #[test] fn test_neg() { fn test(a: Rational, b: Rational) { assert_eq!(-a, b); assert_eq!(-to_big(a), to_big(b)) } test(_0, _0); test(_1_2, _NEG1_2); test(-_1, _1); } #[test] fn test_zero() { assert_eq!(_0 + _0, _0); assert_eq!(_0 * _0, _0); assert_eq!(_0 * _1, _0); assert_eq!(_0 / _NEG1_2, _0); assert_eq!(_0 - _0, _0); } #[test] #[should_panic] fn test_div_0() { let _a = _1 / _0; } #[test] fn test_checked_failures() { let big = Ratio::new(128u8, 1); let small = Ratio::new(1, 128u8); assert_eq!(big.checked_add(&big), None); assert_eq!(small.checked_sub(&big), None); assert_eq!(big.checked_mul(&big), None); assert_eq!(small.checked_div(&big), None); assert_eq!(_1.checked_div(&_0), None); } } #[test] fn test_round() { assert_eq!(_1_3.ceil(), _1); assert_eq!(_1_3.floor(), _0); assert_eq!(_1_3.round(), _0); assert_eq!(_1_3.trunc(), _0); assert_eq!(_NEG1_3.ceil(), _0); assert_eq!(_NEG1_3.floor(), -_1); assert_eq!(_NEG1_3.round(), _0); assert_eq!(_NEG1_3.trunc(), _0); assert_eq!(_2_3.ceil(), _1); assert_eq!(_2_3.floor(), _0); assert_eq!(_2_3.round(), _1); assert_eq!(_2_3.trunc(), _0); assert_eq!(_NEG2_3.ceil(), _0); assert_eq!(_NEG2_3.floor(), -_1); assert_eq!(_NEG2_3.round(), -_1); assert_eq!(_NEG2_3.trunc(), _0); assert_eq!(_1_2.ceil(), _1); assert_eq!(_1_2.floor(), _0); assert_eq!(_1_2.round(), _1); assert_eq!(_1_2.trunc(), _0); assert_eq!(_NEG1_2.ceil(), _0); assert_eq!(_NEG1_2.floor(), -_1); assert_eq!(_NEG1_2.round(), -_1); assert_eq!(_NEG1_2.trunc(), _0); assert_eq!(_1.ceil(), _1); assert_eq!(_1.floor(), _1); assert_eq!(_1.round(), _1); assert_eq!(_1.trunc(), _1); // Overflow checks let _neg1 = Ratio::from_integer(-1); let _large_rat1 = Ratio::new(i32::MAX, i32::MAX - 1); let _large_rat2 = Ratio::new(i32::MAX - 1, i32::MAX); let _large_rat3 = Ratio::new(i32::MIN + 2, i32::MIN + 1); let _large_rat4 = Ratio::new(i32::MIN + 1, i32::MIN + 2); let _large_rat5 = Ratio::new(i32::MIN + 2, i32::MAX); let _large_rat6 = Ratio::new(i32::MAX, i32::MIN + 2); let _large_rat7 = Ratio::new(1, i32::MIN + 1); let _large_rat8 = Ratio::new(1, i32::MAX); assert_eq!(_large_rat1.round(), One::one()); assert_eq!(_large_rat2.round(), One::one()); assert_eq!(_large_rat3.round(), One::one()); assert_eq!(_large_rat4.round(), One::one()); assert_eq!(_large_rat5.round(), _neg1); assert_eq!(_large_rat6.round(), _neg1); assert_eq!(_large_rat7.round(), Zero::zero()); assert_eq!(_large_rat8.round(), Zero::zero()); } #[test] fn test_fract() { assert_eq!(_1.fract(), _0); assert_eq!(_NEG1_2.fract(), _NEG1_2); assert_eq!(_1_2.fract(), _1_2); assert_eq!(_3_2.fract(), _1_2); } #[test] fn test_recip() { assert_eq!(_1 * _1.recip(), _1); assert_eq!(_2 * _2.recip(), _1); assert_eq!(_1_2 * _1_2.recip(), _1); assert_eq!(_3_2 * _3_2.recip(), _1); assert_eq!(_NEG1_2 * _NEG1_2.recip(), _1); assert_eq!(_3_2.recip(), _2_3); assert_eq!(_NEG1_2.recip(), _NEG2); assert_eq!(_NEG1_2.recip().denom(), &1); } #[test] #[should_panic(expected = "== 0")] fn test_recip_fail() { let _a = Ratio::new(0, 1).recip(); } #[test] fn test_pow() { fn test(r: Rational, e: i32, expected: Rational) { assert_eq!(r.pow(e), expected); assert_eq!(Pow::pow(r, e), expected); assert_eq!(Pow::pow(r, &e), expected); assert_eq!(Pow::pow(&r, e), expected); assert_eq!(Pow::pow(&r, &e), expected); } test(_1_2, 2, Ratio::new(1, 4)); test(_1_2, -2, Ratio::new(4, 1)); test(_1, 1, _1); test(_1, i32::MAX, _1); test(_1, i32::MIN, _1); test(_NEG1_2, 2, _1_2.pow(2i32)); test(_NEG1_2, 3, -_1_2.pow(3i32)); test(_3_2, 0, _1); test(_3_2, -1, _3_2.recip()); test(_3_2, 3, Ratio::new(27, 8)); } #[test] #[cfg(feature = "std")] fn test_to_from_str() { use std::string::{String, ToString}; fn test(r: Rational, s: String) { assert_eq!(FromStr::from_str(&s), Ok(r)); assert_eq!(r.to_string(), s); } test(_1, "1".to_string()); test(_0, "0".to_string()); test(_1_2, "1/2".to_string()); test(_3_2, "3/2".to_string()); test(_2, "2".to_string()); test(_NEG1_2, "-1/2".to_string()); } #[test] fn test_from_str_fail() { fn test(s: &str) { let rational: Result = FromStr::from_str(s); assert!(rational.is_err()); } let xs = ["0 /1", "abc", "", "1/", "--1/2", "3/2/1", "1/0"]; for &s in xs.iter() { test(s); } } #[cfg(feature = "bigint")] #[test] fn test_from_float() { use traits::float::FloatCore; fn test(given: T, (numer, denom): (&str, &str)) { let ratio: BigRational = Ratio::from_float(given).unwrap(); assert_eq!( ratio, Ratio::new( FromStr::from_str(numer).unwrap(), FromStr::from_str(denom).unwrap() ) ); } // f32 test(3.14159265359f32, ("13176795", "4194304")); test(2f32.powf(100.), ("1267650600228229401496703205376", "1")); test(-2f32.powf(100.), ("-1267650600228229401496703205376", "1")); test( 1.0 / 2f32.powf(100.), ("1", "1267650600228229401496703205376"), ); test(684729.48391f32, ("1369459", "2")); test(-8573.5918555f32, ("-4389679", "512")); // f64 test(3.14159265359f64, ("3537118876014453", "1125899906842624")); test(2f64.powf(100.), ("1267650600228229401496703205376", "1")); test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1")); test(684729.48391f64, ("367611342500051", "536870912")); test(-8573.5918555f64, ("-4713381968463931", "549755813888")); test( 1.0 / 2f64.powf(100.), ("1", "1267650600228229401496703205376"), ); } #[cfg(feature = "bigint")] #[test] fn test_from_float_fail() { use core::{f32, f64}; assert_eq!(Ratio::from_float(f32::NAN), None); assert_eq!(Ratio::from_float(f32::INFINITY), None); assert_eq!(Ratio::from_float(f32::NEG_INFINITY), None); assert_eq!(Ratio::from_float(f64::NAN), None); assert_eq!(Ratio::from_float(f64::INFINITY), None); assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None); } #[test] fn test_signed() { assert_eq!(_NEG1_2.abs(), _1_2); assert_eq!(_3_2.abs_sub(&_1_2), _1); assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero()); assert_eq!(_1_2.signum(), One::one()); assert_eq!(_NEG1_2.signum(), ->::one()); assert_eq!(_0.signum(), Zero::zero()); assert!(_NEG1_2.is_negative()); assert!(_1_NEG2.is_negative()); assert!(!_NEG1_2.is_positive()); assert!(!_1_NEG2.is_positive()); assert!(_1_2.is_positive()); assert!(_NEG1_NEG2.is_positive()); assert!(!_1_2.is_negative()); assert!(!_NEG1_NEG2.is_negative()); assert!(!_0.is_positive()); assert!(!_0.is_negative()); } #[test] #[cfg(feature = "std")] fn test_hash() { assert!(::hash(&_0) != ::hash(&_1)); assert!(::hash(&_0) != ::hash(&_3_2)); // a == b -> hash(a) == hash(b) let a = Rational::new_raw(4, 2); let b = Rational::new_raw(6, 3); assert_eq!(a, b); assert_eq!(::hash(&a), ::hash(&b)); let a = Rational::new_raw(123456789, 1000); let b = Rational::new_raw(123456789 * 5, 5000); assert_eq!(a, b); assert_eq!(::hash(&a), ::hash(&b)); } #[test] fn test_into_pair() { assert_eq!((0, 1), _0.into()); assert_eq!((-2, 1), _NEG2.into()); assert_eq!((1, -2), _1_NEG2.into()); } #[test] fn test_from_pair() { assert_eq!(_0, Ratio::from((0, 1))); assert_eq!(_1, Ratio::from((1, 1))); assert_eq!(_NEG2, Ratio::from((-2, 1))); assert_eq!(_1_NEG2, Ratio::from((1, -2))); } #[test] fn ratio_iter_sum() { // generic function to assure the iter method can be called // for any Iterator with Item = Ratio or Ratio<&impl Integer> fn iter_sums(slice: &[Ratio]) -> [Ratio; 3] { let mut manual_sum = Ratio::new(T::zero(), T::one()); for ratio in slice { manual_sum = manual_sum + ratio; } [manual_sum, slice.iter().sum(), slice.iter().cloned().sum()] } // collect into array so test works on no_std let mut nums = [Ratio::new(0, 1); 1000]; for (i, r) in (0..1000).map(|n| Ratio::new(n, 500)).enumerate() { nums[i] = r; } let sums = iter_sums(&nums[..]); assert_eq!(sums[0], sums[1]); assert_eq!(sums[0], sums[2]); } #[test] fn ratio_iter_product() { // generic function to assure the iter method can be called // for any Iterator with Item = Ratio or Ratio<&impl Integer> fn iter_products(slice: &[Ratio]) -> [Ratio; 3] { let mut manual_prod = Ratio::new(T::one(), T::one()); for ratio in slice { manual_prod = manual_prod * ratio; } [ manual_prod, slice.iter().product(), slice.iter().cloned().product(), ] } // collect into array so test works on no_std let mut nums = [Ratio::new(0, 1); 1000]; for (i, r) in (0..1000).map(|n| Ratio::new(n, 500)).enumerate() { nums[i] = r; } let products = iter_products(&nums[..]); assert_eq!(products[0], products[1]); assert_eq!(products[0], products[2]); } #[test] fn test_num_zero() { let zero = Rational64::zero(); assert!(zero.is_zero()); let mut r = Rational64::new(123, 456); assert!(!r.is_zero()); assert_eq!(&r + &zero, r); r.set_zero(); assert!(r.is_zero()); } #[test] fn test_num_one() { let one = Rational64::one(); assert!(one.is_one()); let mut r = Rational64::new(123, 456); assert!(!r.is_one()); assert_eq!(&r * &one, r); r.set_one(); assert!(r.is_one()); } } num-rational-0.2.2/.cargo_vcs_info.json0000644000000001120000000000000134740ustar00{ "git": { "sha1": "ebebba97367d08d72387bd790290d87907212b5c" } }