lib.rs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
  2. // file at the top-level directory of this distribution and at
  3. // http://rust-lang.org/COPYRIGHT.
  4. //
  5. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  6. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  7. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  8. // option. This file may not be copied, modified, or distributed
  9. // except according to those terms.
  10. //! Simple numerics.
  11. //!
  12. //! This crate contains arbitrary-sized integer, rational, and complex types.
  13. //!
  14. //! ## Example
  15. //!
  16. //! This example uses the BigRational type and [Newton's method][newt] to
  17. //! approximate a square root to arbitrary precision:
  18. //!
  19. //! ```
  20. //! # #![allow(unstable)]
  21. //! extern crate num;
  22. //!
  23. //! use std::num::FromPrimitive;
  24. //! use num::bigint::BigInt;
  25. //! use num::rational::{Ratio, BigRational};
  26. //!
  27. //! fn approx_sqrt(number: u64, iterations: usize) -> BigRational {
  28. //! let start: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u64(number).unwrap());
  29. //! let mut approx = start.clone();
  30. //!
  31. //! for _ in range(0, iterations) {
  32. //! approx = (&approx + (&start / &approx)) /
  33. //! Ratio::from_integer(FromPrimitive::from_u64(2).unwrap());
  34. //! }
  35. //!
  36. //! approx
  37. //! }
  38. //!
  39. //! fn main() {
  40. //! println!("{}", approx_sqrt(10, 4)); // prints 4057691201/1283082416
  41. //! }
  42. //! ```
  43. //!
  44. //! [newt]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
  45. #![feature(slicing_syntax, collections, core, hash, rand, std_misc)]
  46. #![cfg_attr(test, deny(warnings))]
  47. #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
  48. html_favicon_url = "http://www.rust-lang.org/favicon.ico",
  49. html_root_url = "http://doc.rust-lang.org/num/",
  50. html_playground_url = "http://play.rust-lang.org/")]
  51. extern crate "rustc-serialize" as rustc_serialize;
  52. extern crate core;
  53. pub use bigint::{BigInt, BigUint};
  54. pub use rational::{Rational, BigRational};
  55. pub use complex::Complex;
  56. pub use integer::Integer;
  57. pub use iter::{range, range_inclusive, range_step, range_step_inclusive};
  58. pub use traits::{Num, Zero, One, Signed, Unsigned, Bounded,
  59. Saturating, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv};
  60. #[cfg(test)] use std::hash;
  61. use std::ops::{Mul};
  62. pub mod bigint;
  63. pub mod complex;
  64. pub mod integer;
  65. pub mod iter;
  66. pub mod traits;
  67. pub mod rational;
  68. /// Returns the additive identity, `0`.
  69. #[inline(always)] pub fn zero<T: Zero>() -> T { Zero::zero() }
  70. /// Returns the multiplicative identity, `1`.
  71. #[inline(always)] pub fn one<T: One>() -> T { One::one() }
  72. /// Computes the absolute value.
  73. ///
  74. /// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`
  75. ///
  76. /// For signed integers, `::MIN` will be returned if the number is `::MIN`.
  77. #[inline(always)]
  78. pub fn abs<T: Signed>(value: T) -> T {
  79. value.abs()
  80. }
  81. /// The positive difference of two numbers.
  82. ///
  83. /// Returns zero if `x` is less than or equal to `y`, otherwise the difference
  84. /// between `x` and `y` is returned.
  85. #[inline(always)]
  86. pub fn abs_sub<T: Signed>(x: T, y: T) -> T {
  87. x.abs_sub(&y)
  88. }
  89. /// Returns the sign of the number.
  90. ///
  91. /// For `f32` and `f64`:
  92. ///
  93. /// * `1.0` if the number is positive, `+0.0` or `INFINITY`
  94. /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
  95. /// * `NaN` if the number is `NaN`
  96. ///
  97. /// For signed integers:
  98. ///
  99. /// * `0` if the number is zero
  100. /// * `1` if the number is positive
  101. /// * `-1` if the number is negative
  102. #[inline(always)] pub fn signum<T: Signed>(value: T) -> T { value.signum() }
  103. /// Raises a value to the power of exp, using exponentiation by squaring.
  104. ///
  105. /// # Example
  106. ///
  107. /// ```rust
  108. /// use num;
  109. ///
  110. /// assert_eq!(num::pow(2i, 4), 16);
  111. /// ```
  112. #[inline]
  113. pub fn pow<T: Clone + One + Mul<T, Output = T>>(mut base: T, mut exp: usize) -> T {
  114. if exp == 1 { base }
  115. else {
  116. let mut acc = one::<T>();
  117. while exp > 0 {
  118. if (exp & 1) == 1 {
  119. acc = acc * base.clone();
  120. }
  121. base = base.clone() * base;
  122. exp = exp >> 1;
  123. }
  124. acc
  125. }
  126. }
  127. #[cfg(test)]
  128. fn hash<T: hash::Hash<hash::SipHasher>>(x: &T) -> u64 {
  129. hash::hash::<_, hash::SipHasher>(x)
  130. }