Trait malachite_base::num::basic::floats::PrimitiveFloat
source · pub trait PrimitiveFloat: 'static + Abs<Output = Self> + AbsAssign + Add<Output = Self> + AddAssign<Self> + AddMul<Output = Self> + AddMulAssign<Self, Self> + Ceiling<Output = Self> + CeilingAssign + CeilingLogBase2<Output = i64> + CeilingLogBasePowerOf2<u64, Output = i64> + CheckedLogBase2<Output = i64> + CheckedLogBasePowerOf2<u64, Output = i64> + ConvertibleFrom<u8> + ConvertibleFrom<u16> + ConvertibleFrom<u32> + ConvertibleFrom<u64> + ConvertibleFrom<u128> + ConvertibleFrom<usize> + ConvertibleFrom<i8> + ConvertibleFrom<i16> + ConvertibleFrom<i32> + ConvertibleFrom<i64> + ConvertibleFrom<i128> + ConvertibleFrom<isize> + Copy + Debug + Default + Display + Div<Output = Self> + DivAssign + Floor<Output = Self> + FloorAssign + FloorLogBase2<Output = i64> + FloorLogBasePowerOf2<u64, Output = i64> + FmtRyuString + From<f32> + FromStr + IntegerMantissaAndExponent<u64, i64> + Into<f64> + IsInteger + IsPowerOf2 + Iverson + LowerExp + Min + Max + Mul<Output = Self> + MulAssign<Self> + Named + Neg<Output = Self> + NegAssign + NegativeOne + NextPowerOf2<Output = Self> + NextPowerOf2Assign + One + PartialEq<Self> + PartialOrd<Self> + Pow<i64, Output = Self> + Pow<Self, Output = Self> + PowAssign<i64> + PowAssign<Self> + PowerOf2<i64> + Product + RawMantissaAndExponent<u64, u64> + Rem<Output = Self> + RemAssign<Self> + RoundingFrom<u8> + RoundingFrom<u16> + RoundingFrom<u32> + RoundingFrom<u64> + RoundingFrom<u128> + RoundingFrom<usize> + RoundingFrom<i8> + RoundingFrom<i16> + RoundingFrom<i32> + RoundingFrom<i64> + RoundingFrom<i128> + RoundingFrom<isize> + RoundingInto<u8> + RoundingInto<u16> + RoundingInto<u32> + RoundingInto<u64> + RoundingInto<u128> + RoundingInto<usize> + RoundingInto<i8> + RoundingInto<i16> + RoundingInto<i32> + RoundingInto<i64> + RoundingInto<i128> + RoundingInto<isize> + SciMantissaAndExponent<Self, i64> + Sign + Sized + Sqrt<Output = Self> + SqrtAssign + Square<Output = Self> + SquareAssign + Sub<Output = Self> + SubAssign<Self> + SubMul<Output = Self> + SubMulAssign<Self, Self> + Sum<Self> + Two + UpperExp + Zero {
Show 16 associated constants and 16 methods
const WIDTH: u64;
const MANTISSA_WIDTH: u64;
const MIN_POSITIVE_SUBNORMAL: Self;
const MAX_SUBNORMAL: Self;
const MIN_POSITIVE_NORMAL: Self;
const MAX_FINITE: Self;
const NEGATIVE_ZERO: Self;
const POSITIVE_INFINITY: Self;
const NEGATIVE_INFINITY: Self;
const NAN: Self;
const SMALLEST_UNREPRESENTABLE_UINT: u64;
const LARGEST_ORDERED_REPRESENTATION: u64;
const EXPONENT_WIDTH: u64 = _;
const MIN_NORMAL_EXPONENT: i64 = _;
const MIN_EXPONENT: i64 = _;
const MAX_EXPONENT: i64 = _;
fn is_nan(self) -> bool;
fn is_infinite(self) -> bool;
fn is_finite(self) -> bool;
fn is_normal(self) -> bool;
fn classify(self) -> FpCategory;
fn to_bits(self) -> u64;
fn from_bits(v: u64) -> Self;
fn is_negative_zero(self) -> bool { ... }
fn abs_negative_zero(self) -> Self { ... }
fn abs_negative_zero_assign(&mut self) { ... }
fn next_higher(self) -> Self { ... }
fn next_lower(self) -> Self { ... }
fn to_ordered_representation(self) -> u64 { ... }
fn from_ordered_representation(n: u64) -> Self { ... }
fn precision(self) -> u64 { ... }
fn max_precision_for_sci_exponent(exponent: i64) -> u64 { ... }
}
Expand description
This trait defines functions on primitive float types: f32
and f64
.
Many of the functions here concern exponents and mantissas. We define three ways to express a
float, each with its own exponent and mantissa. In the following, let $x$ be an arbitrary
positive, finite, non-zero, non-NaN float. Let $M$ and $E$ be the mantissa width and exponent
width of the floating point type; for f32
s, this is 23 and 8, and for f64
s it’s 52 and
11.
In the following we assume that $x$ is positive, but you can easily extend these definitions to negative floats by first taking their absolute value.
raw form
The raw exponent and raw mantissa are the actual bit patterns used to represent the components of $x$. The raw exponent $e_r$ is an integer in $[0, 2^E-2]$ and the raw mantissa $m_r$ is an integer in $[0, 2^M-1]$. Since we are dealing with a nonzero $x$, we forbid $e_r$ and $m_r$ from both being zero. We have $$ x = \begin{cases} 2^{2-2^{E-1}-M}m_r & \text{if} \quad e_r = 0, \\ 2^{e_r-2^{E-1}+1}(2^{-M}m_r+1) & \textrm{otherwise}, \end{cases} $$ $$ e_r = \begin{cases} 0 & \text{if} \quad x < 2^{2-2^{E-1}}, \\ \lfloor \log_2 x \rfloor + 2^{E-1} - 1 & \textrm{otherwise}, \end{cases} $$ $$ m_r = \begin{cases} 2^{M+2^{E-1}-2}x & \text{if} \quad x < 2^{2-2^{E-1}}, \\ 2^M \left ( \frac{x}{2^{\lfloor \log_2 x \rfloor}}-1\right ) & \textrm{otherwise}. \end{cases} $$
scientific form
We can write $x = 2^{e_s}m_s$, where $e_s$ is an integer and $m_s$ is a rational number with $1 \leq m_s < 2$. If $x$ is a valid float, the scientific mantissa $m_s$ is always exactly representable as a float of the same type. We have $$ x = 2^{e_s}m_s, $$ $$ e_s = \lfloor \log_2 x \rfloor, $$ $$ m_s = \frac{x}{2^{\lfloor \log_2 x \rfloor}}. $$
integer form
We can also write $x = 2^{e_i}m_i$, where $e_i$ is an integer and $m_i$ is an odd integer. We have $$ x = 2^{e_i}m_i, $$ $e_i$ is the unique integer such that $x/2^{e_i}$is an odd integer, and $$ m_i = \frac{x}{2^{e_i}}. $$
Required Associated Constants§
sourceconst MANTISSA_WIDTH: u64
const MANTISSA_WIDTH: u64
sourceconst MIN_POSITIVE_SUBNORMAL: Self
const MIN_POSITIVE_SUBNORMAL: Self
sourceconst MAX_SUBNORMAL: Self
const MAX_SUBNORMAL: Self
sourceconst MIN_POSITIVE_NORMAL: Self
const MIN_POSITIVE_NORMAL: Self
sourceconst MAX_FINITE: Self
const MAX_FINITE: Self
const NEGATIVE_ZERO: Self
const POSITIVE_INFINITY: Self
const NEGATIVE_INFINITY: Self
const NAN: Self
sourceconst LARGEST_ORDERED_REPRESENTATION: u64
const LARGEST_ORDERED_REPRESENTATION: u64
If you list all floats in increasing order, excluding NaN and giving negative and positive zero separate adjacent spots, this will be index of the last element, positive infinity. It is $2^{M+1}(2^E-1)+1$.
Provided Associated Constants§
sourceconst EXPONENT_WIDTH: u64 = _
const EXPONENT_WIDTH: u64 = _
sourceconst MIN_NORMAL_EXPONENT: i64 = _
const MIN_NORMAL_EXPONENT: i64 = _
sourceconst MIN_EXPONENT: i64 = _
const MIN_EXPONENT: i64 = _
sourceconst MAX_EXPONENT: i64 = _
const MAX_EXPONENT: i64 = _
Required Methods§
fn is_nan(self) -> bool
fn is_infinite(self) -> bool
fn is_finite(self) -> bool
fn is_normal(self) -> bool
fn classify(self) -> FpCategory
fn to_bits(self) -> u64
fn from_bits(v: u64) -> Self
Provided Methods§
sourcefn is_negative_zero(self) -> bool
fn is_negative_zero(self) -> bool
Tests whether self
is negative zero.
Worst-case complexity
Constant time and additional memory.
Examples
use malachite_base::num::basic::floats::PrimitiveFloat;
assert!((-0.0).is_negative_zero());
assert!(!0.0.is_negative_zero());
assert!(!1.0.is_negative_zero());
assert!(!f32::NAN.is_negative_zero());
assert!(!f32::POSITIVE_INFINITY.is_negative_zero());
sourcefn abs_negative_zero(self) -> Self
fn abs_negative_zero(self) -> Self
If self
is negative zero, returns positive zero; otherwise, returns self
.
Worst-case complexity
Constant time and additional memory.
Examples
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
assert_eq!(NiceFloat((-0.0).abs_negative_zero()), NiceFloat(0.0));
assert_eq!(NiceFloat(0.0.abs_negative_zero()), NiceFloat(0.0));
assert_eq!(NiceFloat(1.0.abs_negative_zero()), NiceFloat(1.0));
assert_eq!(NiceFloat((-1.0).abs_negative_zero()), NiceFloat(-1.0));
assert_eq!(NiceFloat(f32::NAN.abs_negative_zero()), NiceFloat(f32::NAN));
sourcefn abs_negative_zero_assign(&mut self)
fn abs_negative_zero_assign(&mut self)
If self
is negative zero, replaces it with positive zero; otherwise, leaves self
unchanged.
Worst-case complexity
Constant time and additional memory.
Examples
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
let mut f = -0.0;
f.abs_negative_zero_assign();
assert_eq!(NiceFloat(f), NiceFloat(0.0));
let mut f = 0.0;
f.abs_negative_zero_assign();
assert_eq!(NiceFloat(f), NiceFloat(0.0));
let mut f = 1.0;
f.abs_negative_zero_assign();
assert_eq!(NiceFloat(f), NiceFloat(1.0));
let mut f = -1.0;
f.abs_negative_zero_assign();
assert_eq!(NiceFloat(f), NiceFloat(-1.0));
let mut f = f32::NAN;
f.abs_negative_zero_assign();
assert_eq!(NiceFloat(f), NiceFloat(f32::NAN));
sourcefn next_higher(self) -> Self
fn next_higher(self) -> Self
Returns the smallest float larger than self
.
Passing -0.0
returns 0.0
; passing NaN
or positive infinity panics.
Worst-case complexity
Constant time and additional memory.
Panics
Panics if self
is NaN
or positive infinity.
Examples
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
assert_eq!(NiceFloat((-0.0f32).next_higher()), NiceFloat(0.0));
assert_eq!(NiceFloat(0.0f32.next_higher()), NiceFloat(1.0e-45));
assert_eq!(NiceFloat(1.0f32.next_higher()), NiceFloat(1.0000001));
assert_eq!(NiceFloat((-1.0f32).next_higher()), NiceFloat(-0.99999994));
sourcefn next_lower(self) -> Self
fn next_lower(self) -> Self
Returns the largest float smaller than self
.
Passing 0.0
returns -0.0
; passing NaN
or negative infinity panics.
Worst-case complexity
Constant time and additional memory.
Panics
Panics if self
is NaN
or negative infinity.
Examples
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::float::NiceFloat;
assert_eq!(NiceFloat(0.0f32.next_lower()), NiceFloat(-0.0));
assert_eq!(NiceFloat((-0.0f32).next_lower()), NiceFloat(-1.0e-45));
assert_eq!(NiceFloat(1.0f32.next_lower()), NiceFloat(0.99999994));
assert_eq!(NiceFloat((-1.0f32).next_lower()), NiceFloat(-1.0000001));
Examples found in repository?
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
fn get_ys(&self, &sci_exponent: &i64) -> ExhaustivePrimitiveFloatsWithExponentInRange<T> {
let a = if sci_exponent == self.a_sci_exponent {
self.a
} else {
T::from_integer_mantissa_and_exponent(1, sci_exponent).unwrap()
};
let b = if sci_exponent == self.b_sci_exponent {
self.b
} else {
T::from_integer_mantissa_and_exponent(1, sci_exponent + 1)
.unwrap()
.next_lower()
};
exhaustive_primitive_floats_with_sci_exponent_in_range(a, b, sci_exponent)
}
}
#[inline]
fn exhaustive_positive_finite_primitive_floats_in_range_helper<T: PrimitiveFloat>(
a: T,
b: T,
) -> ExhaustiveDependentPairs<
i64,
T,
RulerSequence<usize>,
ExhaustivePositiveFinitePrimitiveFloatsInRangeGenerator<T>,
ExhaustiveSignedRange<i64>,
ExhaustivePrimitiveFloatsWithExponentInRange<T>,
> {
assert!(a.is_finite());
assert!(b.is_finite());
assert!(a > T::ZERO);
assert!(a <= b);
let (am, ae) = a.raw_mantissa_and_exponent();
let (bm, be) = b.raw_mantissa_and_exponent();
let a_sci_exponent = if ae == 0 {
i64::wrapping_from(am.significant_bits()) + T::MIN_EXPONENT - 1
} else {
i64::wrapping_from(ae) - T::MAX_EXPONENT
};
let b_sci_exponent = if be == 0 {
i64::wrapping_from(bm.significant_bits()) + T::MIN_EXPONENT - 1
} else {
i64::wrapping_from(be) - T::MAX_EXPONENT
};
exhaustive_dependent_pairs(
ruler_sequence(),
exhaustive_signed_inclusive_range(a_sci_exponent, b_sci_exponent),
ExhaustivePositiveFinitePrimitiveFloatsInRangeGenerator {
a,
b,
a_sci_exponent,
b_sci_exponent,
phantom: PhantomData,
},
)
}
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct ExhaustivePositiveFinitePrimitiveFloatsInRange<T: PrimitiveFloat>(
ExhaustiveDependentPairs<
i64,
T,
RulerSequence<usize>,
ExhaustivePositiveFinitePrimitiveFloatsInRangeGenerator<T>,
ExhaustiveSignedRange<i64>,
ExhaustivePrimitiveFloatsWithExponentInRange<T>,
>,
);
impl<T: PrimitiveFloat> Iterator for ExhaustivePositiveFinitePrimitiveFloatsInRange<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.0.next().map(|p| p.1)
}
}
#[doc(hidden)]
#[inline]
pub fn exhaustive_positive_finite_primitive_floats_in_range<T: PrimitiveFloat>(
a: T,
b: T,
) -> ExhaustivePositiveFinitePrimitiveFloatsInRange<T> {
ExhaustivePositiveFinitePrimitiveFloatsInRange(
exhaustive_positive_finite_primitive_floats_in_range_helper(a, b),
)
}
#[doc(hidden)]
#[derive(Clone, Debug)]
pub enum ExhaustiveNonzeroFinitePrimitiveFloatsInRange<T: PrimitiveFloat> {
AllPositive(ExhaustivePositiveFinitePrimitiveFloatsInRange<T>),
AllNegative(ExhaustivePositiveFinitePrimitiveFloatsInRange<T>),
PositiveAndNegative(
bool,
ExhaustivePositiveFinitePrimitiveFloatsInRange<T>,
ExhaustivePositiveFinitePrimitiveFloatsInRange<T>,
),
}
impl<T: PrimitiveFloat> Iterator for ExhaustiveNonzeroFinitePrimitiveFloatsInRange<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
match self {
ExhaustiveNonzeroFinitePrimitiveFloatsInRange::AllPositive(ref mut xs) => xs.next(),
ExhaustiveNonzeroFinitePrimitiveFloatsInRange::AllNegative(ref mut xs) => {
xs.next().map(T::neg)
}
ExhaustiveNonzeroFinitePrimitiveFloatsInRange::PositiveAndNegative(
ref mut toggle,
ref mut pos_xs,
ref mut neg_xs,
) => {
toggle.not_assign();
if *toggle {
pos_xs.next().or_else(|| neg_xs.next().map(T::neg))
} else {
neg_xs.next().map(T::neg).or_else(|| pos_xs.next())
}
}
}
}
}
#[doc(hidden)]
#[inline]
pub fn exhaustive_nonzero_finite_primitive_floats_in_range<T: PrimitiveFloat>(
a: T,
b: T,
) -> ExhaustiveNonzeroFinitePrimitiveFloatsInRange<T> {
assert!(a.is_finite());
assert!(b.is_finite());
assert!(a != T::ZERO);
assert!(b != T::ZERO);
assert!(a <= b);
if a > T::ZERO {
ExhaustiveNonzeroFinitePrimitiveFloatsInRange::AllPositive(
exhaustive_positive_finite_primitive_floats_in_range(a, b),
)
} else if b < T::ZERO {
ExhaustiveNonzeroFinitePrimitiveFloatsInRange::AllNegative(
exhaustive_positive_finite_primitive_floats_in_range(-b, -a),
)
} else {
ExhaustiveNonzeroFinitePrimitiveFloatsInRange::PositiveAndNegative(
false,
exhaustive_positive_finite_primitive_floats_in_range(T::MIN_POSITIVE_SUBNORMAL, b),
exhaustive_positive_finite_primitive_floats_in_range(T::MIN_POSITIVE_SUBNORMAL, -a),
)
}
}
/// Generates all primitive floats in an interval.
///
/// This `enum` is created by [`exhaustive_primitive_float_range`] and
/// [`exhaustive_primitive_float_inclusive_range`]; see their documentation for more.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug)]
pub enum ExhaustivePrimitiveFloatInclusiveRange<T: PrimitiveFloat> {
JustSpecials(IntoIter<T>),
NotJustSpecials(Chain<IntoIter<T>, ExhaustiveNonzeroFinitePrimitiveFloatsInRange<T>>),
}
impl<T: PrimitiveFloat> Iterator for ExhaustivePrimitiveFloatInclusiveRange<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
match self {
ExhaustivePrimitiveFloatInclusiveRange::JustSpecials(ref mut xs) => xs.next(),
ExhaustivePrimitiveFloatInclusiveRange::NotJustSpecials(ref mut xs) => xs.next(),
}
}
}
/// Generates all primitive floats in the half-open interval $[a, b)$.
///
/// Positive and negative zero are treated as two distinct values, with negative zero being smaller
/// than zero.
///
/// The floats are generated in a way such that simpler floats (with lower precision) are generated
/// first. To generate floats in ascending order instead, use [`primitive_float_increasing_range`]
/// instead.
///
/// `NiceFloat(a)` must be less than or equal to `NiceFloat(b)`. If `NiceFloat(a)` and
/// `NiceFloat(b)` are equal, the range is empty.
///
/// Let $\varphi$ be
/// [`to_ordered_representation`](super::basic::floats::PrimitiveFloat::to_ordered_representation):
///
/// The output length is $\varphi(b) - \varphi(a)$.
///
/// # Complexity per iteration
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `NiceFloat(a) > NiceFloat(b)`.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::exhaustive::exhaustive_primitive_float_range;
/// use malachite_base::num::float::NiceFloat;
///
/// assert_eq!(
/// prefix_to_string(
/// exhaustive_primitive_float_range::<f32>(core::f32::consts::E, core::f32::consts::PI)
/// .map(NiceFloat),
/// 50
/// ),
/// "[3.0, 2.75, 2.875, 3.125, 2.8125, 2.9375, 3.0625, 2.71875, 2.78125, 2.84375, 2.90625, \
/// 2.96875, 3.03125, 3.09375, 2.734375, 2.765625, 2.796875, 2.828125, 2.859375, 2.890625, \
/// 2.921875, 2.953125, 2.984375, 3.015625, 3.046875, 3.078125, 3.109375, 3.140625, \
/// 2.7265625, 2.7421875, 2.7578125, 2.7734375, 2.7890625, 2.8046875, 2.8203125, 2.8359375, \
/// 2.8515625, 2.8671875, 2.8828125, 2.8984375, 2.9140625, 2.9296875, 2.9453125, 2.9609375, \
/// 2.9765625, 2.9921875, 3.0078125, 3.0234375, 3.0390625, 3.0546875, ...]"
/// );
/// ```
#[inline]
pub fn exhaustive_primitive_float_range<T: PrimitiveFloat>(
a: T,
b: T,
) -> ExhaustivePrimitiveFloatInclusiveRange<T> {
assert!(!a.is_nan());
assert!(!b.is_nan());
assert!(NiceFloat(a) <= NiceFloat(b));
if NiceFloat(a) == NiceFloat(b) {
ExhaustivePrimitiveFloatInclusiveRange::JustSpecials(Vec::new().into_iter())
} else {
exhaustive_primitive_float_inclusive_range(a, b.next_lower())
}
}
More examples
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
fn next(&mut self) -> Option<T> {
let sci_exponent = self.sci_exponents.next().unwrap();
let ae = self.ae;
let be = self.be;
let am = self.am;
let bm = self.bm;
let precision_ranges = self
.precision_range_map
.entry(sci_exponent)
.or_insert_with(|| {
let am = if sci_exponent == ae {
am
} else {
T::from_integer_mantissa_and_exponent(1, sci_exponent)
.unwrap()
.raw_mantissa()
};
let bm = if sci_exponent == be {
bm
} else {
T::from_integer_mantissa_and_exponent(1, sci_exponent + 1)
.unwrap()
.next_lower()
.raw_mantissa()
};
(1..=T::max_precision_for_sci_exponent(sci_exponent))
.filter_map(|p| mantissas_inclusive::<T>(sci_exponent, am, bm, p))
.collect_vec()
});
assert!(!precision_ranges.is_empty());
let i = self.precision_indices.next().unwrap() % precision_ranges.len();
let t = precision_ranges[i];
let mantissa = (self.ranges.next_in_inclusive_range(t.1, t.2) << 1) | 1;
Some(T::from_integer_mantissa_and_exponent(mantissa, t.0).unwrap())
}
}
fn special_random_positive_finite_float_inclusive_range<T: PrimitiveFloat>(
seed: Seed,
a: T,
b: T,
mean_sci_exponent_numerator: u64,
mean_sci_exponent_denominator: u64,
mean_precision_numerator: u64,
mean_precision_denominator: u64,
) -> SpecialRandomPositiveFiniteFloatInclusiveRange<T> {
assert!(a.is_finite());
assert!(b.is_finite());
assert!(a > T::ZERO);
assert!(a <= b);
let (am, ae) = a.raw_mantissa_and_exponent();
let (bm, be) = b.raw_mantissa_and_exponent();
let ae = if ae == 0 {
i64::wrapping_from(am.significant_bits()) + T::MIN_EXPONENT - 1
} else {
i64::wrapping_from(ae) - T::MAX_EXPONENT
};
let be = if be == 0 {
i64::wrapping_from(bm.significant_bits()) + T::MIN_EXPONENT - 1
} else {
i64::wrapping_from(be) - T::MAX_EXPONENT
};
SpecialRandomPositiveFiniteFloatInclusiveRange {
phantom: PhantomData,
am,
bm,
ae,
be,
sci_exponents: geometric_random_signed_inclusive_range(
seed.fork("exponents"),
ae,
be,
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
),
precision_range_map: HashMap::new(),
precision_indices: geometric_random_unsigneds(
seed.fork("precisions"),
mean_precision_numerator,
mean_precision_denominator,
),
ranges: variable_range_generator(seed.fork("ranges")),
}
}
#[allow(clippy::large_enum_variant)]
#[doc(hidden)]
#[derive(Clone, Debug)]
pub enum SpecialRandomFiniteFloatInclusiveRange<T: PrimitiveFloat> {
AllPositive(SpecialRandomPositiveFiniteFloatInclusiveRange<T>),
AllNegative(SpecialRandomPositiveFiniteFloatInclusiveRange<T>),
PositiveAndNegative(
RandomBools,
SpecialRandomPositiveFiniteFloatInclusiveRange<T>,
SpecialRandomPositiveFiniteFloatInclusiveRange<T>,
),
}
impl<T: PrimitiveFloat> Iterator for SpecialRandomFiniteFloatInclusiveRange<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
match self {
SpecialRandomFiniteFloatInclusiveRange::AllPositive(ref mut xs) => xs.next(),
SpecialRandomFiniteFloatInclusiveRange::AllNegative(ref mut xs) => {
xs.next().map(|x| -x)
}
SpecialRandomFiniteFloatInclusiveRange::PositiveAndNegative(
ref mut bs,
ref mut xs,
ref mut ys,
) => {
if bs.next().unwrap() {
xs.next()
} else {
ys.next().map(|x| -x)
}
}
}
}
}
fn special_random_finite_float_inclusive_range<T: PrimitiveFloat>(
seed: Seed,
a: T,
b: T,
mean_sci_exponent_numerator: u64,
mean_sci_exponent_denominator: u64,
mean_precision_numerator: u64,
mean_precision_denominator: u64,
) -> SpecialRandomFiniteFloatInclusiveRange<T> {
assert!(a.is_finite());
assert!(b.is_finite());
assert_ne!(a, T::ZERO);
assert_ne!(b, T::ZERO);
assert!(a <= b);
if a > T::ZERO {
SpecialRandomFiniteFloatInclusiveRange::AllPositive(
special_random_positive_finite_float_inclusive_range(
seed,
a,
b,
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
mean_precision_numerator,
mean_precision_denominator,
),
)
} else if b < T::ZERO {
SpecialRandomFiniteFloatInclusiveRange::AllNegative(
special_random_positive_finite_float_inclusive_range(
seed,
-b,
-a,
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
mean_precision_numerator,
mean_precision_denominator,
),
)
} else {
SpecialRandomFiniteFloatInclusiveRange::PositiveAndNegative(
random_bools(seed.fork("bs")),
special_random_positive_finite_float_inclusive_range(
seed,
T::MIN_POSITIVE_SUBNORMAL,
b,
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
mean_precision_numerator,
mean_precision_denominator,
),
special_random_positive_finite_float_inclusive_range(
seed,
T::MIN_POSITIVE_SUBNORMAL,
-a,
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
mean_precision_numerator,
mean_precision_denominator,
),
)
}
}
/// Generates random primitive floats in a range.
///
/// This `enum` is created by [`special_random_primitive_float_range`]; see its documentation for
/// more.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug)]
pub enum SpecialRandomFloatInclusiveRange<T: PrimitiveFloat> {
OnlySpecial(RandomValuesFromVec<T>),
NoSpecial(Box<SpecialRandomFiniteFloatInclusiveRange<T>>),
Special(Box<WithSpecialValues<SpecialRandomFiniteFloatInclusiveRange<T>>>),
}
impl<T: PrimitiveFloat> Iterator for SpecialRandomFloatInclusiveRange<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
match self {
SpecialRandomFloatInclusiveRange::OnlySpecial(ref mut xs) => xs.next(),
SpecialRandomFloatInclusiveRange::NoSpecial(ref mut xs) => xs.next(),
SpecialRandomFloatInclusiveRange::Special(ref mut xs) => xs.next(),
}
}
}
/// Generates random primitive floats in the half-open interval $[a, b)$.
///
/// Simpler floats (those with a lower absolute sci-exponent or precision) are more likely to be
/// chosen. You can specify the numerator and denominator of the probability that any special
/// values (positive or negative zero or infinity) are generated, provided that they are in the
/// range. You can also specify the mean absolute sci-exponent and precision by passing the
/// numerators and denominators of their means of the finite floats.
///
/// But note that the means are only approximate, since the distributions we are sampling are
/// truncated geometric, and their exact means are somewhat annoying to deal with. The practical
/// implications are that
/// - The actual mean is lower than the specified means.
/// - However, increasing the approximate mean increases the actual means, so this still works as a
/// mechanism for controlling the sci-exponent and precision.
/// - The specified sci-exponent mean must be greater the smallest absolute of any sci-exponent of
/// a float in the range, and the precision mean greater than 2, but they may be as high as you
/// like.
///
/// But note that the specified means are only approximate, since the distributions we are sampling
/// are truncated geometric, and their exact means are somewhat annoying to deal with. The
/// practical implications are that
/// - The actual means are slightly lower than the specified means.
/// - However, increasing the specified means increases the actual means, so this still works as a
/// mechanism for controlling the sci-exponent and precision.
/// - The specified sci-exponent mean must be greater the smallest absolute value of any
/// sci-exponent of a float in the range, and the precision mean greater than 2, but they may be
/// as high as you like.
///
/// `NaN` is never generated.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Panics
/// Panics if $a$ or $b$ are `NaN`, if $a$ is greater than or equal to $b$ in the `NiceFloat`
/// ordering, if any of the denominators are zero, if the special probability is greater than 1, if
/// the mean precision is less than 2, or if the mean sci-exponent is less than or equal to the
/// minimum absolute value of any sci-exponent in the range.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::basic::floats::PrimitiveFloat;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::special_random_primitive_float_range;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// special_random_primitive_float_range::<f32>(
/// EXAMPLE_SEED,
/// core::f32::consts::E,
/// core::f32::consts::PI,
/// 10,
/// 1,
/// 10,
/// 1,
/// 1,
/// 100
/// ).map(NiceFloat),
/// 20
/// ),
/// "[2.9238281, 2.953125, 3.0, 2.8671875, 2.8125, 3.125, 3.015625, 2.8462658, 3.140625, \
/// 2.875, 3.0, 2.75, 3.0, 2.71875, 2.75, 3.0214844, 2.970642, 3.0179443, 2.968872, 2.75, ...]"
/// );
/// ```
pub fn special_random_primitive_float_range<T: PrimitiveFloat>(
seed: Seed,
a: T,
b: T,
mean_sci_exponent_numerator: u64,
mean_sci_exponent_denominator: u64,
mean_precision_numerator: u64,
mean_precision_denominator: u64,
mean_special_p_numerator: u64,
mean_special_p_denominator: u64,
) -> SpecialRandomFloatInclusiveRange<T> {
assert!(!a.is_nan());
assert!(!b.is_nan());
assert!(NiceFloat(a) < NiceFloat(b));
special_random_primitive_float_inclusive_range(
seed,
a,
b.next_lower(),
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
mean_precision_numerator,
mean_precision_denominator,
mean_special_p_numerator,
mean_special_p_denominator,
)
}
sourcefn to_ordered_representation(self) -> u64
fn to_ordered_representation(self) -> u64
Maps self
to an integer. The map preserves ordering, and adjacent floats are mapped to
adjacent integers.
Negative infinity is mapped to 0, and positive infinity is mapped to the largest value,
LARGEST_ORDERED_REPRESENTATION
.
Negative and positive zero are mapped to distinct adjacent values. Passing in NaN
panics.
The inverse operation is
from_ordered_representation
.
Worst-case complexity
Constant time and additional memory.
Panics
Panics if self
is NaN
.
Examples
use malachite_base::num::basic::floats::PrimitiveFloat;
assert_eq!(f32::NEGATIVE_INFINITY.to_ordered_representation(), 0);
assert_eq!((-0.0f32).to_ordered_representation(), 2139095040);
assert_eq!(0.0f32.to_ordered_representation(), 2139095041);
assert_eq!(1.0f32.to_ordered_representation(), 3204448257);
assert_eq!(
f32::POSITIVE_INFINITY.to_ordered_representation(),
4278190081
);
Examples found in repository?
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
pub fn primitive_float_increasing_range<T: PrimitiveFloat>(
a: T,
b: T,
) -> PrimitiveFloatIncreasingRange<T> {
assert!(!a.is_nan());
assert!(!b.is_nan());
if NiceFloat(a) > NiceFloat(b) {
panic!(
"a must be less than or equal to b. a: {}, b: {}",
NiceFloat(a),
NiceFloat(b)
);
}
PrimitiveFloatIncreasingRange {
phantom: PhantomData,
xs: primitive_int_increasing_range(
a.to_ordered_representation(),
b.to_ordered_representation(),
),
}
}
/// Generates all primitive floats in the closed interval $[a, b]$, in ascending order.
///
/// Positive and negative zero are treated as two distinct values, with negative zero being smaller
/// than zero.
///
/// `NiceFloat(a)` must be less than or equal to `NiceFloat(b)`. If `NiceFloat(a)` and
/// `NiceFloat(b)` are equal, the range contains a single element.
///
/// Let $\varphi$ be
/// [`to_ordered_representation`](super::basic::floats::PrimitiveFloat::to_ordered_representation):
///
/// The output is $(\varphi^{-1}(k))_{k=\varphi(a)}^\varphi(b)$.
///
/// The output length is $\varphi(b) - \varphi(a) + 1$.
///
/// # Complexity per iteration
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `NiceFloat(a) > NiceFloat(b)`.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::exhaustive::primitive_float_increasing_inclusive_range;
/// use malachite_base::num::float::NiceFloat;
///
/// assert_eq!(
/// prefix_to_string(
/// primitive_float_increasing_inclusive_range::<f32>(1.0, 2.0).map(NiceFloat),
/// 20
/// ),
/// "[1.0, 1.0000001, 1.0000002, 1.0000004, 1.0000005, 1.0000006, 1.0000007, 1.0000008, \
/// 1.000001, 1.0000011, 1.0000012, 1.0000013, 1.0000014, 1.0000015, 1.0000017, 1.0000018, \
/// 1.0000019, 1.000002, 1.0000021, 1.0000023, ...]"
/// );
/// assert_eq!(
/// prefix_to_string(
/// primitive_float_increasing_inclusive_range::<f32>(1.0, 2.0).rev().map(NiceFloat),
/// 20
/// ),
/// "[2.0, 1.9999999, 1.9999998, 1.9999996, 1.9999995, 1.9999994, 1.9999993, 1.9999992, \
/// 1.999999, 1.9999989, 1.9999988, 1.9999987, 1.9999986, 1.9999985, 1.9999983, 1.9999982, \
/// 1.9999981, 1.999998, 1.9999979, 1.9999977, ...]"
/// );
/// ```
pub fn primitive_float_increasing_inclusive_range<T: PrimitiveFloat>(
a: T,
b: T,
) -> PrimitiveFloatIncreasingRange<T> {
assert!(!a.is_nan());
assert!(!b.is_nan());
if NiceFloat(a) > NiceFloat(b) {
panic!(
"a must be less than or equal to b. a: {}, b: {}",
NiceFloat(a),
NiceFloat(b)
);
}
PrimitiveFloatIncreasingRange {
phantom: PhantomData,
xs: primitive_int_increasing_inclusive_range(
a.to_ordered_representation(),
b.to_ordered_representation(),
),
}
}
More examples
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
pub fn random_primitive_float_range<T: PrimitiveFloat>(
seed: Seed,
a: T,
b: T,
) -> RandomPrimitiveFloatRange<T> {
assert!(!a.is_nan());
assert!(!b.is_nan());
if NiceFloat(a) >= NiceFloat(b) {
panic!(
"a must be less than b. a: {}, b: {}",
NiceFloat(a),
NiceFloat(b)
);
}
RandomPrimitiveFloatRange {
phantom: PhantomData,
xs: random_unsigned_range(
seed,
a.to_ordered_representation(),
b.to_ordered_representation(),
),
}
}
/// Generates random primitive floats in the closed interval $[a, b]$.
///
/// Every float within the range has an equal probability of being chosen. This does not mean that
/// the distribution approximates a uniform distribution over the reals. For example, if the range
/// is $[0, 2]$, a float in $[1/4, 1/2)$ is as likely to be chosen as a float in $[1, 2)$, since
/// these subranges contain an equal number of floats.
///
/// Positive and negative zero are treated as two distinct values, with negative zero being smaller
/// than zero.
///
/// $a$ must be less than or equal to $b$.
///
/// `NaN` is never generated.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Panics
/// Panics if $a > b$.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::random_primitive_float_inclusive_range;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// random_primitive_float_inclusive_range::<f32>(EXAMPLE_SEED, -0.1, 0.1).map(NiceFloat),
/// 10
/// ),
/// "[5.664681e-11, 1.2492925e-35, 2.3242339e-29, 4.699183e-7, -2.8244436e-36, -2.264039e-37, \
/// -0.0000017299129, 1.40616e-23, 2.7418007e-27, 1.5418819e-16, ...]"
/// );
/// ```
#[inline]
pub fn random_primitive_float_inclusive_range<T: PrimitiveFloat>(
seed: Seed,
a: T,
b: T,
) -> RandomPrimitiveFloatInclusiveRange<T> {
assert!(!a.is_nan());
assert!(!b.is_nan());
if NiceFloat(a) > NiceFloat(b) {
panic!(
"a must be less than or equal to b. a: {}, b: {}",
NiceFloat(a),
NiceFloat(b)
);
}
RandomPrimitiveFloatInclusiveRange {
phantom: PhantomData,
xs: random_unsigned_inclusive_range(
seed,
a.to_ordered_representation(),
b.to_ordered_representation(),
),
}
}
/// Generates finite positive primitive floats.
///
/// Every float within the range has an equal probability of being chosen. This does not mean that
/// the distribution approximates a uniform distribution over the reals. For example, a float in
/// $[1/4, 1/2)$ is as likely to be chosen as a float in $[1, 2)$, since these subranges contain an
/// equal number of floats.
///
/// Positive zero is generated; negative zero is not. `NaN` is not generated either.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::random_positive_finite_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// random_positive_finite_primitive_floats::<f32>(EXAMPLE_SEED).map(NiceFloat),
/// 10
/// ),
/// "[9.5715654e26, 209.6476, 386935780.0, 7.965817e30, 0.00021030706, 0.0027270128, \
/// 3.4398167e-34, 2.3397111e14, 44567765000.0, 2.3479653e21, ...]"
/// );
/// ```
#[inline]
pub fn random_positive_finite_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
) -> RandomPrimitiveFloatInclusiveRange<T> {
random_primitive_float_inclusive_range(seed, T::MIN_POSITIVE_SUBNORMAL, T::MAX_FINITE)
}
/// Generates finite negative primitive floats.
///
/// Every float within the range has an equal probability of being chosen. This does not mean that
/// the distribution approximates a uniform distribution over the reals. For example, a float in
/// $(-1/2, 1/4]$ is as likely to be chosen as a float in $(-2, -1]$, since these subranges contain
/// an equal number of floats.
///
/// Negative zero is generated; positive zero is not. `NaN` is not generated either.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::random_negative_finite_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// random_negative_finite_primitive_floats::<f32>(EXAMPLE_SEED).map(NiceFloat),
/// 10
/// ),
/// "[-2.3484663e-27, -0.010641626, -5.8060583e-9, -2.8182442e-31, -10462.532, -821.12994, \
/// -6.303163e33, -9.50376e-15, -4.9561126e-11, -8.565163e-22, ...]"
/// );
/// ```
#[inline]
pub fn random_negative_finite_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
) -> RandomPrimitiveFloatInclusiveRange<T> {
random_primitive_float_inclusive_range(seed, -T::MAX_FINITE, -T::MIN_POSITIVE_SUBNORMAL)
}
/// Generates finite nonzero primitive floats.
///
/// Every float within the range has an equal probability of being chosen. This does not mean that
/// the distribution approximates a uniform distribution over the reals. For example, a float in
/// $[1/4, 1/2)$ is as likely to be chosen as a float in $[1, 2)$, since these subranges contain an
/// equal number of floats.
///
/// Neither positive nor negative zero are generated. `NaN` is not generated either.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::random_nonzero_finite_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// random_nonzero_finite_primitive_floats::<f32>(EXAMPLE_SEED).map(NiceFloat),
/// 10
/// ),
/// "[-2.3484663e-27, 2.287989e-18, -2.0729893e-12, 3.360012e28, -9.021723e-32, 3564911.2, \
/// -0.0000133769445, -1.8855448e18, 8.2494555e-29, 2.2178014e-38, ...]"
/// );
/// ```
#[inline]
pub fn random_nonzero_finite_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
) -> NonzeroValues<RandomPrimitiveFloatInclusiveRange<T>> {
nonzero_values(random_finite_primitive_floats(seed))
}
/// Generates finite primitive floats.
///
/// Every float within the range has an equal probability of being chosen. This does not mean that
/// the distribution approximates a uniform distribution over the reals. For example, a float in
/// $[1/4, 1/2)$ is as likely to be chosen as a float in $[1, 2)$, since these subranges contain an
/// equal number of floats.
///
/// Positive zero and negative zero are both generated. `NaN` is not.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::random_finite_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(random_finite_primitive_floats::<f32>(EXAMPLE_SEED).map(NiceFloat), 10),
/// "[-2.3484663e-27, 2.287989e-18, -2.0729893e-12, 3.360012e28, -9.021723e-32, 3564911.2, \
/// -0.0000133769445, -1.8855448e18, 8.2494555e-29, 2.2178014e-38, ...]"
/// );
/// ```
#[inline]
pub fn random_finite_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
) -> RandomPrimitiveFloatInclusiveRange<T> {
random_primitive_float_inclusive_range(seed, -T::MAX_FINITE, T::MAX_FINITE)
}
/// Generates positive primitive floats.
///
/// Every float within the range has an equal probability of being chosen. This does not mean that
/// the distribution approximates a uniform distribution over the reals. For example, a float in
/// $[1/4, 1/2)$ is as likely to be chosen as a float in $[1, 2)$, since these subranges contain an
/// equal number of floats.
///
/// Positive zero is generated; negative zero is not. `NaN` is not generated either.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::random_positive_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(random_positive_primitive_floats::<f32>(EXAMPLE_SEED).map(NiceFloat), 10),
/// "[9.5715654e26, 209.6476, 386935780.0, 7.965817e30, 0.00021030706, 0.0027270128, \
/// 3.4398167e-34, 2.3397111e14, 44567765000.0, 2.3479653e21, ...]"
/// );
/// ```
#[inline]
pub fn random_positive_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
) -> RandomPrimitiveFloatInclusiveRange<T> {
random_primitive_float_inclusive_range(seed, T::MIN_POSITIVE_SUBNORMAL, T::POSITIVE_INFINITY)
}
/// Generates negative primitive floats.
///
/// Every float within the range has an equal probability of being chosen. This does not mean that
/// the distribution approximates a uniform distribution over the reals. For example, a float in
/// $(-1/2, -1/4]$ is as likely to be chosen as a float in $(-2, -1]$, since these subranges
/// contain an equal number of floats.
///
/// Negative zero is generated; positive zero is not. `NaN` is not generated either.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::random_negative_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(random_negative_primitive_floats::<f32>(EXAMPLE_SEED).map(NiceFloat), 10),
/// "[-2.3484665e-27, -0.010641627, -5.8060587e-9, -2.8182444e-31, -10462.533, -821.13, \
/// -6.3031636e33, -9.5037605e-15, -4.956113e-11, -8.565164e-22, ...]"
/// );
/// ```
#[inline]
pub fn random_negative_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
) -> RandomPrimitiveFloatInclusiveRange<T> {
random_primitive_float_inclusive_range(seed, T::NEGATIVE_INFINITY, -T::MIN_POSITIVE_SUBNORMAL)
}
/// Generates nonzero primitive floats.
///
/// Every float within the range has an equal probability of being chosen. This does not mean that
/// the distribution approximates a uniform distribution over the reals. For example, a float in
/// $[1/4, 1/2)$ is as likely to be chosen as a float in $[1, 2)$, since these subranges contain an
/// equal number of floats.
///
/// Neither positive nor negative zero are generated. `NaN` is not generated either.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::random_nonzero_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(random_nonzero_primitive_floats::<f32>(EXAMPLE_SEED).map(NiceFloat), 10),
/// "[-2.3484665e-27, 2.2879888e-18, -2.0729896e-12, 3.3600117e28, -9.0217234e-32, 3564911.0, \
/// -0.000013376945, -1.885545e18, 8.249455e-29, 2.2178013e-38, ...]",
/// );
/// ```
#[inline]
pub fn random_nonzero_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
) -> NonzeroValues<RandomPrimitiveFloats<T>> {
nonzero_values(random_primitive_floats(seed))
}
/// Generates random primitive floats.
///
/// This `struct` is created by [`random_primitive_floats`]; see its documentation for more.
#[derive(Clone, Debug)]
pub struct RandomPrimitiveFloats<T: PrimitiveFloat> {
phantom: PhantomData<*const T>,
pub(crate) xs: RandomUnsignedInclusiveRange<u64>,
nan: u64,
}
impl<T: PrimitiveFloat> Iterator for RandomPrimitiveFloats<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
self.xs.next().map(|x| {
if x == self.nan {
T::NAN
} else {
T::from_ordered_representation(x)
}
})
}
}
/// Generates finite primitive floats.
///
/// Every float has an equal probability of being chosen. This does not mean that the distribution
/// approximates a uniform distribution over the reals. For example, a float in $[1/4, 1/2)$ is as
/// likely to be chosen as a float in $[1, 2)$, since these subranges contain an equal number of
/// floats.
///
/// Positive zero, negative zero, and `NaN` are all generated.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::random_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(random_primitive_floats::<f32>(EXAMPLE_SEED).map(NiceFloat), 10),
/// "[-2.3484665e-27, 2.2879888e-18, -2.0729896e-12, 3.3600117e28, -9.0217234e-32, 3564911.0, \
/// -0.000013376945, -1.885545e18, 8.249455e-29, 2.2178013e-38, ...]"
/// );
/// ```
#[inline]
pub fn random_primitive_floats<T: PrimitiveFloat>(seed: Seed) -> RandomPrimitiveFloats<T> {
let nan = T::POSITIVE_INFINITY.to_ordered_representation() + 1;
RandomPrimitiveFloats {
phantom: PhantomData,
xs: random_unsigned_inclusive_range(seed, 0, nan),
nan,
}
}
sourcefn from_ordered_representation(n: u64) -> Self
fn from_ordered_representation(n: u64) -> Self
Maps a non-negative integer, less than or equal to
LARGEST_ORDERED_REPRESENTATION
, to a
float. The map preserves ordering, and adjacent integers are mapped to adjacent floats.
Zero is mapped to negative infinity, and
LARGEST_ORDERED_REPRESENTATION
is
mapped to positive infinity. Negative and positive zero are produced by two distinct
adjacent integers. NaN
is never produced.
The inverse operation is
to_ordered_representation
.
Worst-case complexity
Constant time and additional memory.
Panics
Panics if self
is greater than
LARGEST_ORDERED_REPRESENTATION
.
Examples
use malachite_base::num::basic::floats::PrimitiveFloat;
assert_eq!(f32::from_ordered_representation(0), f32::NEGATIVE_INFINITY);
assert_eq!(f32::from_ordered_representation(2139095040), -0.0f32);
assert_eq!(f32::from_ordered_representation(2139095041), 0.0f32);
assert_eq!(f32::from_ordered_representation(3204448257), 1.0f32);
assert_eq!(
f32::from_ordered_representation(4278190081),
f32::POSITIVE_INFINITY
);
sourcefn precision(self) -> u64
fn precision(self) -> u64
Returns the precision of a nonzero finite floating-point number.
The precision is the number of significant bits of the integer mantissa. For example, the floats with precision 1 are the powers of 2, those with precision 2 are 3 times a power of 2, those with precision 3 are 5 or 7 times a power of 2, and so on.
Worst-case complexity
Constant time and additional memory.
Panics
Panics if self
is zero, infinite, or NaN
.
Examples
use malachite_base::num::basic::floats::PrimitiveFloat;
assert_eq!(1.0.precision(), 1);
assert_eq!(2.0.precision(), 1);
assert_eq!(3.0.precision(), 2);
assert_eq!(1.5.precision(), 2);
assert_eq!(1.234f32.precision(), 23);
sourcefn max_precision_for_sci_exponent(exponent: i64) -> u64
fn max_precision_for_sci_exponent(exponent: i64) -> u64
Given a scientific exponent, returns the largest possible precision for a float with that exponent.
See the documentation of the precision
function for a
definition of precision.
For exponents greater than or equal to
MIN_NORMAL_EXPONENT
, the maximum precision is one
more than the mantissa width. For smaller exponents (corresponding to the subnormal range),
the precision is lower.
Worst-case complexity
Constant time and additional memory.
Panics
Panics if self
is less than MIN_EXPONENT
or greater
than MAX_EXPONENT
.
Examples
use malachite_base::num::basic::floats::PrimitiveFloat;
assert_eq!(f32::max_precision_for_sci_exponent(0), 24);
assert_eq!(f32::max_precision_for_sci_exponent(127), 24);
assert_eq!(f32::max_precision_for_sci_exponent(-149), 1);
assert_eq!(f32::max_precision_for_sci_exponent(-148), 2);
assert_eq!(f32::max_precision_for_sci_exponent(-147), 3);
Examples found in repository?
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
pub fn exhaustive_primitive_floats_with_sci_exponent_and_precision<T: PrimitiveFloat>(
sci_exponent: i64,
precision: u64,
) -> ConstantPrecisionPrimitiveFloats<T> {
assert!(sci_exponent >= T::MIN_EXPONENT);
assert!(sci_exponent <= T::MAX_EXPONENT);
assert_ne!(precision, 0);
let max_precision = T::max_precision_for_sci_exponent(sci_exponent);
assert!(precision <= max_precision);
let increment = u64::power_of_2(max_precision - precision + 1);
let first_mantissa = if precision == 1 {
1
} else {
u64::power_of_2(precision - 1) | 1
};
let first = T::from_integer_mantissa_and_exponent(
first_mantissa,
sci_exponent - i64::exact_from(precision) + 1,
)
.unwrap()
.to_bits();
let count = if precision == 1 {
1
} else {
u64::power_of_2(precision - 2)
};
ConstantPrecisionPrimitiveFloats {
phantom: PhantomData,
n: first,
increment,
i: 0,
count,
}
}
#[doc(hidden)]
#[derive(Clone, Debug)]
struct PrimitiveFloatsWithExponentGenerator<T: PrimitiveFloat> {
phantom: PhantomData<*const T>,
sci_exponent: i64,
}
impl<T: PrimitiveFloat>
ExhaustiveDependentPairsYsGenerator<u64, T, ConstantPrecisionPrimitiveFloats<T>>
for PrimitiveFloatsWithExponentGenerator<T>
{
#[inline]
fn get_ys(&self, &precision: &u64) -> ConstantPrecisionPrimitiveFloats<T> {
exhaustive_primitive_floats_with_sci_exponent_and_precision(self.sci_exponent, precision)
}
}
#[inline]
fn exhaustive_primitive_floats_with_sci_exponent_helper<T: PrimitiveFloat>(
sci_exponent: i64,
) -> LexDependentPairs<
u64,
T,
PrimitiveFloatsWithExponentGenerator<T>,
PrimitiveIntIncreasingRange<u64>,
ConstantPrecisionPrimitiveFloats<T>,
> {
lex_dependent_pairs(
primitive_int_increasing_inclusive_range(
1,
T::max_precision_for_sci_exponent(sci_exponent),
),
PrimitiveFloatsWithExponentGenerator {
phantom: PhantomData,
sci_exponent,
},
)
}
/// Generates all finite positive primitive floats with a specified `sci_exponent`.
///
/// This `struct` is created by [`exhaustive_primitive_floats_with_sci_exponent`]; see its
/// documentation for more.
#[derive(Clone, Debug)]
pub struct ExhaustivePrimitiveFloatsWithExponent<T: PrimitiveFloat>(
LexDependentPairs<
u64,
T,
PrimitiveFloatsWithExponentGenerator<T>,
PrimitiveIntIncreasingRange<u64>,
ConstantPrecisionPrimitiveFloats<T>,
>,
);
impl<T: PrimitiveFloat> Iterator for ExhaustivePrimitiveFloatsWithExponent<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.0.next().map(|p| p.1)
}
}
/// Generates all finite positive primitive floats with a specified sci-exponent.
///
/// Positive and negative zero are both excluded.
///
/// A finite positive primitive float may be uniquely expressed as $x = m_s2^e_s$, where
/// $1 \leq m_s < 2$ and $e_s$ is an integer; then $e$ is the sci-exponent. An integer $e_s$ occurs
/// as the sci-exponent of a float iff $2-2^{E-1}-M \leq e_s < 2^{E-1}$.
///
/// If $e_s \geq 2-2^{E-1}$ (the float is normal), the output length is $2^M$.
/// - For [`f32`], this is $2^{23}$, or 8388608.
/// - For [`f64`], this is $2^{52}$, or 4503599627370496.
///
/// If $e_s < 2-2^{E-1}$ (the float is subnormal), the output length is $2^{e_s+2^{E-1}+M-2}$.
/// - For [`f32`], this is $2^{e_s+149}$.
/// - For [`f64`], this is $2^{e_s+1074}$.
///
/// # Complexity per iteration
/// Constant time and additional memory.
///
/// # Panics
/// Panics if the sci-exponent is less than
/// [`MIN_EXPONENT`](super::basic::floats::PrimitiveFloat::MIN_EXPONENT)` or greater than
/// [`MAX_EXPONENT`](super::basic::floats::PrimitiveFloat::MAX_EXPONENT).
///
/// # Examples
/// ```
/// use itertools::Itertools;
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::exhaustive::exhaustive_primitive_floats_with_sci_exponent;
/// use malachite_base::num::float::NiceFloat;
///
/// assert_eq!(
/// prefix_to_string(
/// exhaustive_primitive_floats_with_sci_exponent::<f32>(0).map(NiceFloat),
/// 20
/// ),
/// "[1.0, 1.5, 1.25, 1.75, 1.125, 1.375, 1.625, 1.875, 1.0625, 1.1875, 1.3125, 1.4375, \
/// 1.5625, 1.6875, 1.8125, 1.9375, 1.03125, 1.09375, 1.15625, 1.21875, ...]",
/// );
/// assert_eq!(
/// prefix_to_string(
/// exhaustive_primitive_floats_with_sci_exponent::<f32>(4).map(NiceFloat),
/// 20
/// ),
/// "[16.0, 24.0, 20.0, 28.0, 18.0, 22.0, 26.0, 30.0, 17.0, 19.0, 21.0, 23.0, 25.0, 27.0, \
/// 29.0, 31.0, 16.5, 17.5, 18.5, 19.5, ...]"
/// );
/// assert_eq!(
/// exhaustive_primitive_floats_with_sci_exponent::<f32>(-147).map(NiceFloat).collect_vec(),
/// [6.0e-45, 8.0e-45, 7.0e-45, 1.0e-44].iter().copied().map(NiceFloat).collect_vec()
/// );
/// ```
#[inline]
pub fn exhaustive_primitive_floats_with_sci_exponent<T: PrimitiveFloat>(
sci_exponent: i64,
) -> ExhaustivePrimitiveFloatsWithExponent<T> {
ExhaustivePrimitiveFloatsWithExponent(exhaustive_primitive_floats_with_sci_exponent_helper(
sci_exponent,
))
}
#[doc(hidden)]
#[derive(Clone, Debug)]
struct ExhaustivePositiveFinitePrimitiveFloatsGenerator<T: PrimitiveFloat> {
phantom: PhantomData<*const T>,
}
impl<T: PrimitiveFloat>
ExhaustiveDependentPairsYsGenerator<i64, T, ExhaustivePrimitiveFloatsWithExponent<T>>
for ExhaustivePositiveFinitePrimitiveFloatsGenerator<T>
{
#[inline]
fn get_ys(&self, &sci_exponent: &i64) -> ExhaustivePrimitiveFloatsWithExponent<T> {
exhaustive_primitive_floats_with_sci_exponent(sci_exponent)
}
}
#[inline]
fn exhaustive_positive_finite_primitive_floats_helper<T: PrimitiveFloat>(
) -> ExhaustiveDependentPairs<
i64,
T,
RulerSequence<usize>,
ExhaustivePositiveFinitePrimitiveFloatsGenerator<T>,
ExhaustiveSignedRange<i64>,
ExhaustivePrimitiveFloatsWithExponent<T>,
> {
exhaustive_dependent_pairs(
ruler_sequence(),
exhaustive_signed_inclusive_range(T::MIN_EXPONENT, T::MAX_EXPONENT),
ExhaustivePositiveFinitePrimitiveFloatsGenerator {
phantom: PhantomData,
},
)
}
/// Generates all finite positive primitive floats.
///
/// This `struct` is created by [`exhaustive_positive_finite_primitive_floats`]; see its
/// documentation for more.
#[derive(Clone, Debug)]
pub struct ExhaustivePositiveFinitePrimitiveFloats<T: PrimitiveFloat>(
ExhaustiveDependentPairs<
i64,
T,
RulerSequence<usize>,
ExhaustivePositiveFinitePrimitiveFloatsGenerator<T>,
ExhaustiveSignedRange<i64>,
ExhaustivePrimitiveFloatsWithExponent<T>,
>,
);
impl<T: PrimitiveFloat> Iterator for ExhaustivePositiveFinitePrimitiveFloats<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.0.next().map(|p| p.1)
}
}
/// Generates all finite positive primitive floats.
///
/// Positive and negative zero are both excluded.
///
/// Roughly speaking, the simplest floats are generated first. If you want to generate the floats in
/// ascending order instead, use [`positive_finite_primitive_floats_increasing`].
///
/// The output length is $2^M(2^E-1)-1$.
/// - For [`f32`], this is $2^{31}-2^{23}-1$, or 2139095039.
/// - For [`f64`], this is $2^{63}-2^{52}-1$, or 9218868437227405311.
///
/// # Complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::exhaustive::exhaustive_positive_finite_primitive_floats;
/// use malachite_base::num::float::NiceFloat;
///
/// assert_eq!(
/// prefix_to_string(exhaustive_positive_finite_primitive_floats::<f32>().map(NiceFloat), 50),
/// "[1.0, 2.0, 1.5, 0.5, 1.25, 3.0, 1.75, 4.0, 1.125, 2.5, 1.375, 0.75, 1.625, 3.5, 1.875, \
/// 0.25, 1.0625, 2.25, 1.1875, 0.625, 1.3125, 2.75, 1.4375, 6.0, 1.5625, 3.25, 1.6875, 0.875, \
/// 1.8125, 3.75, 1.9375, 8.0, 1.03125, 2.125, 1.09375, 0.5625, 1.15625, 2.375, 1.21875, 5.0, \
/// 1.28125, 2.625, 1.34375, 0.6875, 1.40625, 2.875, 1.46875, 0.375, 1.53125, 3.125, ...]"
/// );
/// ```
#[inline]
pub fn exhaustive_positive_finite_primitive_floats<T: PrimitiveFloat>(
) -> ExhaustivePositiveFinitePrimitiveFloats<T> {
ExhaustivePositiveFinitePrimitiveFloats(exhaustive_positive_finite_primitive_floats_helper())
}
/// Generates all finite negative primitive floats.
///
/// This `struct` is created by [`exhaustive_negative_finite_primitive_floats`]; see its
/// documentation for more.
#[derive(Clone, Debug)]
pub struct ExhaustiveNegativeFinitePrimitiveFloats<T: PrimitiveFloat>(
ExhaustivePositiveFinitePrimitiveFloats<T>,
);
impl<T: PrimitiveFloat> Iterator for ExhaustiveNegativeFinitePrimitiveFloats<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.0.next().map(|f| -f)
}
}
/// Generates all finite negative primitive floats.
///
/// Positive and negative zero are both excluded.
///
/// Roughly speaking, the simplest floats are generated first. If you want to generate the floats in
/// ascending order instead, use [`negative_finite_primitive_floats_increasing`].
///
/// The output length is $2^M(2^E-1)-1$.
/// - For [`f32`], this is $2^{31}-2^{23}-1$, or 2139095039.
/// - For [`f64`], this is $2^{63}-2^{52}-1$, or 9218868437227405311.
///
/// # Complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::exhaustive::exhaustive_negative_finite_primitive_floats;
/// use malachite_base::num::float::NiceFloat;
///
/// assert_eq!(
/// prefix_to_string(exhaustive_negative_finite_primitive_floats::<f32>().map(NiceFloat), 50),
/// "[-1.0, -2.0, -1.5, -0.5, -1.25, -3.0, -1.75, -4.0, -1.125, -2.5, -1.375, -0.75, -1.625, \
/// -3.5, -1.875, -0.25, -1.0625, -2.25, -1.1875, -0.625, -1.3125, -2.75, -1.4375, -6.0, \
/// -1.5625, -3.25, -1.6875, -0.875, -1.8125, -3.75, -1.9375, -8.0, -1.03125, -2.125, \
/// -1.09375, -0.5625, -1.15625, -2.375, -1.21875, -5.0, -1.28125, -2.625, -1.34375, -0.6875, \
/// -1.40625, -2.875, -1.46875, -0.375, -1.53125, -3.125, ...]"
/// );
/// ```
#[inline]
pub fn exhaustive_negative_finite_primitive_floats<T: PrimitiveFloat>(
) -> ExhaustiveNegativeFinitePrimitiveFloats<T> {
ExhaustiveNegativeFinitePrimitiveFloats(exhaustive_positive_finite_primitive_floats())
}
/// Generates all finite nonzero primitive floats.
///
/// This `struct` is created by [`exhaustive_nonzero_finite_primitive_floats`]; see its
/// documentation for more.
#[derive(Clone, Debug)]
pub struct ExhaustiveNonzeroFinitePrimitiveFloats<T: PrimitiveFloat> {
toggle: bool,
xs: ExhaustivePositiveFinitePrimitiveFloats<T>,
x: T,
}
impl<T: PrimitiveFloat> Iterator for ExhaustiveNonzeroFinitePrimitiveFloats<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.toggle.not_assign();
Some(if self.toggle {
self.x = self.xs.next().unwrap();
self.x
} else {
-self.x
})
}
}
/// Generates all finite nonzero primitive floats.
///
/// Positive and negative zero are both excluded.
///
/// Roughly speaking, the simplest floats are generated first. If you want to generate the floats in
/// ascending order instead, use [`nonzero_finite_primitive_floats_increasing`].
///
/// The output length is $2^{M+1}(2^E-1)-2$.
/// - For [`f32`], this is $2^{32}-2^{24}-2$, or 4278190078.
/// - For [`f64`], this is $2^{64}-2^{53}-2$, or 18437736874454810622.
///
/// # Complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::exhaustive::exhaustive_nonzero_finite_primitive_floats;
/// use malachite_base::num::float::NiceFloat;
///
/// assert_eq!(
/// prefix_to_string(exhaustive_nonzero_finite_primitive_floats::<f32>().map(NiceFloat), 50),
/// "[1.0, -1.0, 2.0, -2.0, 1.5, -1.5, 0.5, -0.5, 1.25, -1.25, 3.0, -3.0, 1.75, -1.75, 4.0, \
/// -4.0, 1.125, -1.125, 2.5, -2.5, 1.375, -1.375, 0.75, -0.75, 1.625, -1.625, 3.5, -3.5, \
/// 1.875, -1.875, 0.25, -0.25, 1.0625, -1.0625, 2.25, -2.25, 1.1875, -1.1875, 0.625, -0.625, \
/// 1.3125, -1.3125, 2.75, -2.75, 1.4375, -1.4375, 6.0, -6.0, 1.5625, -1.5625, ...]"
/// );
/// ```
#[inline]
pub fn exhaustive_nonzero_finite_primitive_floats<T: PrimitiveFloat>(
) -> ExhaustiveNonzeroFinitePrimitiveFloats<T> {
ExhaustiveNonzeroFinitePrimitiveFloats {
toggle: false,
xs: exhaustive_positive_finite_primitive_floats(),
x: T::ZERO,
}
}
/// Generates all finite primitive floats.
///
/// Positive and negative zero are both included.
///
/// Roughly speaking, the simplest floats are generated first. If you want to generate the floats in
/// ascending order instead, use [`finite_primitive_floats_increasing`].
///
/// The output length is $2^{M+1}(2^E-1)$.
/// - For [`f32`], this is $2^{32}-2^{24}$, or 4278190080.
/// - For [`f64`], this is $2^{64}-2^{53}$, or 18437736874454810624.
///
/// # Complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::exhaustive::exhaustive_finite_primitive_floats;
/// use malachite_base::num::float::NiceFloat;
///
/// assert_eq!(
/// prefix_to_string(exhaustive_finite_primitive_floats::<f32>().map(NiceFloat), 50),
/// "[0.0, -0.0, 1.0, -1.0, 2.0, -2.0, 1.5, -1.5, 0.5, -0.5, 1.25, -1.25, 3.0, -3.0, 1.75, \
/// -1.75, 4.0, -4.0, 1.125, -1.125, 2.5, -2.5, 1.375, -1.375, 0.75, -0.75, 1.625, -1.625, \
/// 3.5, -3.5, 1.875, -1.875, 0.25, -0.25, 1.0625, -1.0625, 2.25, -2.25, 1.1875, -1.1875, \
/// 0.625, -0.625, 1.3125, -1.3125, 2.75, -2.75, 1.4375, -1.4375, 6.0, -6.0, ...]"
/// );
/// ```
#[inline]
pub fn exhaustive_finite_primitive_floats<T: PrimitiveFloat>(
) -> Chain<IntoIter<T>, ExhaustiveNonzeroFinitePrimitiveFloats<T>> {
vec![T::ZERO, T::NEGATIVE_ZERO]
.into_iter()
.chain(exhaustive_nonzero_finite_primitive_floats())
}
/// Generates all positive primitive floats.
///
/// Positive and negative zero are both excluded.
///
/// Roughly speaking, the simplest floats are generated first. If you want to generate the floats in
/// ascending order instead, use [`positive_primitive_floats_increasing`].
///
/// The output length is $2^M(2^E-1)$.
/// - For [`f32`]
/// , this is $2^{31}-2^{23}$, or 2139095040.
/// - For [`f64`]
/// , this is $2^{63}-2^{52}$, or 9218868437227405312.
///
/// # Complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::basic::floats::PrimitiveFloat;
/// use malachite_base::num::exhaustive::exhaustive_positive_primitive_floats;
/// use malachite_base::num::float::NiceFloat;
///
/// assert_eq!(
/// prefix_to_string(exhaustive_positive_primitive_floats::<f32>().map(NiceFloat), 50),
/// "[Infinity, 1.0, 2.0, 1.5, 0.5, 1.25, 3.0, 1.75, 4.0, 1.125, 2.5, 1.375, 0.75, 1.625, \
/// 3.5, 1.875, 0.25, 1.0625, 2.25, 1.1875, 0.625, 1.3125, 2.75, 1.4375, 6.0, 1.5625, 3.25, \
/// 1.6875, 0.875, 1.8125, 3.75, 1.9375, 8.0, 1.03125, 2.125, 1.09375, 0.5625, 1.15625, \
/// 2.375, 1.21875, 5.0, 1.28125, 2.625, 1.34375, 0.6875, 1.40625, 2.875, 1.46875, 0.375, \
/// 1.53125, ...]"
/// );
/// ```
#[inline]
pub fn exhaustive_positive_primitive_floats<T: PrimitiveFloat>(
) -> Chain<Once<T>, ExhaustivePositiveFinitePrimitiveFloats<T>> {
once(T::POSITIVE_INFINITY).chain(exhaustive_positive_finite_primitive_floats())
}
/// Generates all negative primitive floats.
///
/// Positive and negative zero are both excluded.
///
/// Roughly speaking, the simplest floats are generated first. If you want to generate the floats in
/// ascending order instead, use [`negative_primitive_floats_increasing`].
///
/// The output length is $2^M(2^E-1)$.
/// - For [`f32`], this is $2^{31}-2^{23}$, or 2139095040.
/// - For [`f64`], this is $2^{63}-2^{52}$, or 9218868437227405312.
///
/// # Complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::basic::floats::PrimitiveFloat;
/// use malachite_base::num::exhaustive::exhaustive_negative_primitive_floats;
/// use malachite_base::num::float::NiceFloat;
///
/// assert_eq!(
/// prefix_to_string(exhaustive_negative_primitive_floats::<f32>().map(NiceFloat), 50),
/// "[-Infinity, -1.0, -2.0, -1.5, -0.5, -1.25, -3.0, -1.75, -4.0, -1.125, -2.5, -1.375, \
/// -0.75, -1.625, -3.5, -1.875, -0.25, -1.0625, -2.25, -1.1875, -0.625, -1.3125, -2.75, \
/// -1.4375, -6.0, -1.5625, -3.25, -1.6875, -0.875, -1.8125, -3.75, -1.9375, -8.0, -1.03125, \
/// -2.125, -1.09375, -0.5625, -1.15625, -2.375, -1.21875, -5.0, -1.28125, -2.625, -1.34375, \
/// -0.6875, -1.40625, -2.875, -1.46875, -0.375, -1.53125, ...]"
/// );
/// ```
#[inline]
pub fn exhaustive_negative_primitive_floats<T: PrimitiveFloat>(
) -> Chain<Once<T>, ExhaustiveNegativeFinitePrimitiveFloats<T>> {
once(T::NEGATIVE_INFINITY).chain(exhaustive_negative_finite_primitive_floats())
}
/// Generates all nonzero primitive floats.
///
/// Positive and negative zero are both excluded. NaN is excluded as well.
///
/// Roughly speaking, the simplest floats are generated first. If you want to generate the floats in
/// ascending order instead, use [`nonzero_primitive_floats_increasing`].
///
/// The output length is $2^{M+1}(2^E-1)$.
/// - For [`f32`], this is $2^{32}-2^{24}$, or 4278190080.
/// - For [`f64`], this is $2^{64}-2^{53}$, or 18437736874454810624.
///
/// # Complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::basic::floats::PrimitiveFloat;
/// use malachite_base::num::exhaustive::exhaustive_nonzero_primitive_floats;
/// use malachite_base::num::float::NiceFloat;
///
/// assert_eq!(
/// prefix_to_string(exhaustive_nonzero_primitive_floats::<f32>().map(NiceFloat), 50),
/// "[Infinity, -Infinity, 1.0, -1.0, 2.0, -2.0, 1.5, -1.5, 0.5, -0.5, 1.25, -1.25, 3.0, \
/// -3.0, 1.75, -1.75, 4.0, -4.0, 1.125, -1.125, 2.5, -2.5, 1.375, -1.375, 0.75, -0.75, \
/// 1.625, -1.625, 3.5, -3.5, 1.875, -1.875, 0.25, -0.25, 1.0625, -1.0625, 2.25, -2.25, \
/// 1.1875, -1.1875, 0.625, -0.625, 1.3125, -1.3125, 2.75, -2.75, 1.4375, -1.4375, 6.0, -6.0, \
/// ...]"
/// );
/// ```
#[inline]
pub fn exhaustive_nonzero_primitive_floats<T: PrimitiveFloat>(
) -> Chain<IntoIter<T>, ExhaustiveNonzeroFinitePrimitiveFloats<T>> {
vec![T::POSITIVE_INFINITY, T::NEGATIVE_INFINITY]
.into_iter()
.chain(exhaustive_nonzero_finite_primitive_floats())
}
/// Generates all primitive floats.
///
/// Positive and negative zero are both included.
///
/// Roughly speaking, the simplest floats are generated first. If you want to generate the floats
/// (except `NaN`) in ascending order instead, use [`primitive_floats_increasing`].
///
/// The output length is $2^{M+1}(2^E-1)+2$.
/// - For [`f32`], this is $2^{32}-2^{24}+2$, or 4278190082.
/// - For [`f64`], this is $2^{64}-2^{53}+2$, or 18437736874454810626.
///
/// # Complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::basic::floats::PrimitiveFloat;
/// use malachite_base::num::exhaustive::exhaustive_primitive_floats;
/// use malachite_base::num::float::NiceFloat;
///
/// assert_eq!(
/// prefix_to_string(exhaustive_primitive_floats::<f32>().map(NiceFloat), 50),
/// "[NaN, Infinity, -Infinity, 0.0, -0.0, 1.0, -1.0, 2.0, -2.0, 1.5, -1.5, 0.5, -0.5, 1.25, \
/// -1.25, 3.0, -3.0, 1.75, -1.75, 4.0, -4.0, 1.125, -1.125, 2.5, -2.5, 1.375, -1.375, 0.75, \
/// -0.75, 1.625, -1.625, 3.5, -3.5, 1.875, -1.875, 0.25, -0.25, 1.0625, -1.0625, 2.25, \
/// -2.25, 1.1875, -1.1875, 0.625, -0.625, 1.3125, -1.3125, 2.75, -2.75, 1.4375, ...]"
/// );
/// ```
#[inline]
pub fn exhaustive_primitive_floats<T: PrimitiveFloat>(
) -> Chain<IntoIter<T>, ExhaustiveNonzeroFinitePrimitiveFloats<T>> {
vec![T::NAN, T::POSITIVE_INFINITY, T::NEGATIVE_INFINITY, T::ZERO, T::NEGATIVE_ZERO]
.into_iter()
.chain(exhaustive_nonzero_finite_primitive_floats())
}
pub_test! {exhaustive_primitive_floats_with_sci_exponent_and_precision_in_range<T: PrimitiveFloat>(
a: T,
b: T,
sci_exponent: i64,
precision: u64
) -> ConstantPrecisionPrimitiveFloats<T> {
assert!(a.is_finite());
assert!(b.is_finite());
assert!(a > T::ZERO);
assert!(b > T::ZERO);
assert!(sci_exponent >= T::MIN_EXPONENT);
assert!(sci_exponent <= T::MAX_EXPONENT);
let (am, ae) = a.raw_mantissa_and_exponent();
let (bm, be) = b.raw_mantissa_and_exponent();
let ae_actual_sci_exponent = if ae == 0 {
i64::wrapping_from(am.significant_bits()) + T::MIN_EXPONENT - 1
} else {
i64::wrapping_from(ae) - T::MAX_EXPONENT
};
let be_actual_sci_exponent = if be == 0 {
i64::wrapping_from(bm.significant_bits()) + T::MIN_EXPONENT - 1
} else {
i64::wrapping_from(be) - T::MAX_EXPONENT
};
assert_eq!(ae_actual_sci_exponent, sci_exponent);
assert_eq!(be_actual_sci_exponent, sci_exponent);
assert!(am <= bm);
assert_ne!(precision, 0);
let max_precision = T::max_precision_for_sci_exponent(sci_exponent);
assert!(precision <= max_precision);
if precision == 1 && am == 0 {
return ConstantPrecisionPrimitiveFloats {
phantom: PhantomData,
n: a.to_bits(),
increment: 0,
i: 0,
count: 1,
};
}
let trailing_zeros = max_precision - precision;
let increment = u64::power_of_2(trailing_zeros + 1);
let mut start_mantissa = am.round_to_multiple_of_power_of_2(trailing_zeros, RoundingMode::Up);
if !start_mantissa.get_bit(trailing_zeros) {
start_mantissa.set_bit(trailing_zeros);
}
if start_mantissa > bm {
return ConstantPrecisionPrimitiveFloats::default();
}
let mut end_mantissa = bm.round_to_multiple_of_power_of_2(trailing_zeros, RoundingMode::Down);
if !end_mantissa.get_bit(trailing_zeros) {
let adjust = u64::power_of_2(trailing_zeros);
if adjust > end_mantissa {
return ConstantPrecisionPrimitiveFloats::default();
}
end_mantissa -= adjust;
}
assert!(start_mantissa <= end_mantissa);
let count = ((end_mantissa - start_mantissa) >> (trailing_zeros + 1)) + 1;
let first = T::from_raw_mantissa_and_exponent(start_mantissa, ae).to_bits();
ConstantPrecisionPrimitiveFloats {
phantom: PhantomData,
n: first,
increment,
i: 0,
count,
}
}}
#[derive(Clone, Debug)]
struct PrimitiveFloatsWithExponentInRangeGenerator<T: PrimitiveFloat> {
a: T,
b: T,
sci_exponent: i64,
phantom: PhantomData<*const T>,
}
impl<T: PrimitiveFloat>
ExhaustiveDependentPairsYsGenerator<u64, T, ConstantPrecisionPrimitiveFloats<T>>
for PrimitiveFloatsWithExponentInRangeGenerator<T>
{
#[inline]
fn get_ys(&self, &precision: &u64) -> ConstantPrecisionPrimitiveFloats<T> {
exhaustive_primitive_floats_with_sci_exponent_and_precision_in_range(
self.a,
self.b,
self.sci_exponent,
precision,
)
}
}
#[inline]
fn exhaustive_primitive_floats_with_sci_exponent_in_range_helper<T: PrimitiveFloat>(
a: T,
b: T,
sci_exponent: i64,
) -> LexDependentPairs<
u64,
T,
PrimitiveFloatsWithExponentInRangeGenerator<T>,
PrimitiveIntIncreasingRange<u64>,
ConstantPrecisionPrimitiveFloats<T>,
> {
lex_dependent_pairs(
primitive_int_increasing_inclusive_range(
1,
T::max_precision_for_sci_exponent(sci_exponent),
),
PrimitiveFloatsWithExponentInRangeGenerator {
a,
b,
sci_exponent,
phantom: PhantomData,
},
)
}
More examples
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
fn next(&mut self) -> Option<T> {
let sci_exponent = self.sci_exponents.next().unwrap();
let mean_precision_n = self.mean_precision_n;
let mean_precision_d = self.mean_precision_d;
let seed = self.seed;
let precisions = self.range_map.entry(sci_exponent).or_insert_with(move || {
geometric_random_unsigned_inclusive_range(
seed.fork(&sci_exponent.to_string()),
1,
T::max_precision_for_sci_exponent(sci_exponent),
mean_precision_n,
mean_precision_d,
)
});
let precision = precisions.next().unwrap();
let mantissa = if precision == 1 {
1
} else {
// e.g. if precision is 4, generate odd values from 1001 through 1111, inclusive
let x = self.ranges.next_in_range(
u64::power_of_2(precision - 2),
u64::power_of_2(precision - 1),
);
(x << 1) | 1
};
T::from_integer_mantissa_and_exponent(
mantissa,
sci_exponent - i64::wrapping_from(precision) + 1,
)
}
}
/// Generates finite positive primitive floats.
///
/// Simpler floats (those with a lower absolute sci-exponent or precision) are more likely to be
/// chosen. You can specify the mean absolute sci-exponent and precision by passing the numerators
/// and denominators of their means.
///
/// But note that the specified means are only approximate, since the distributions we are sampling
/// are truncated geometric, and their exact means are somewhat annoying to deal with. The
/// practical implications are that
/// - The actual means are slightly lower than the specified means.
/// - However, increasing the specified means increases the actual means, so this still works as a
/// mechanism for controlling the sci-exponent and precision.
/// - The specified sci-exponent mean must be greater than 0 and the precision mean greater than 2,
/// but they may be as high as you like.
///
/// Positive zero is generated; negative zero is not. `NaN` is not generated either.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::special_random_positive_finite_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// special_random_positive_finite_primitive_floats::<f32>(EXAMPLE_SEED, 10, 1, 10, 1)
/// .map(NiceFloat),
/// 20
/// ),
/// "[0.80126953, 0.0000013709068, 0.015609741, 0.98552704, 65536.0, 0.008257866, \
/// 0.017333984, 2.25, 7.7089844, 0.00004425831, 0.40625, 24576.0, 37249.0, 1.1991882, \
/// 32.085938, 0.4375, 0.0012359619, 1536.0, 0.22912993, 0.0015716553, ...]"
/// );
/// ```
pub fn special_random_positive_finite_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
mean_sci_exponent_numerator: u64,
mean_sci_exponent_denominator: u64,
mean_precision_numerator: u64,
mean_precision_denominator: u64,
) -> SpecialRandomPositiveFiniteFloats<T> {
assert_ne!(mean_precision_denominator, 0);
assert!(mean_precision_numerator > mean_precision_denominator);
SpecialRandomPositiveFiniteFloats {
seed: seed.fork("precisions"),
sci_exponents: geometric_random_signed_inclusive_range(
EXAMPLE_SEED.fork("exponents"),
T::MIN_EXPONENT,
T::MAX_EXPONENT,
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
),
range_map: HashMap::new(),
ranges: variable_range_generator(seed.fork("ranges")),
mean_precision_n: mean_precision_numerator,
mean_precision_d: mean_precision_denominator,
phantom: PhantomData,
}
}
/// Generates negative finite primitive floats.
///
/// This `struct` is created by [`special_random_negative_finite_primitive_floats`]; see its
/// documentation for more.
#[derive(Clone, Debug)]
pub struct SpecialRandomNegativeFiniteFloats<T: PrimitiveFloat>(
SpecialRandomPositiveFiniteFloats<T>,
);
impl<T: PrimitiveFloat> Iterator for SpecialRandomNegativeFiniteFloats<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.0.next().map(|f| -f)
}
}
/// Generates finite negative primitive floats.
///
/// Simpler floats (those with a lower absolute sci-exponent or precision) are more likely to be
/// chosen. You can specify the mean absolute sci-exponent and precision by passing the numerators
/// and denominators of their means.
///
/// But note that the specified means are only approximate, since the distributions we are sampling
/// are truncated geometric, and their exact means are somewhat annoying to deal with. The
/// practical implications are that
/// - The actual means are slightly lower than the specified means.
/// - However, increasing the specified means increases the actual means, so this still works as a
/// mechanism for controlling the sci-exponent and precision.
/// - The specified sci-exponent mean must be greater than 0 and the precision mean greater than 2,
/// but they may be as high as you like.
///
/// Negative zero is generated; positive zero is not. `NaN` is not generated either.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::special_random_negative_finite_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// special_random_negative_finite_primitive_floats::<f32>(EXAMPLE_SEED, 10, 1, 10, 1)
/// .map(NiceFloat),
/// 20
/// ),
/// "[-0.80126953, -0.0000013709068, -0.015609741, -0.98552704, -65536.0, -0.008257866, \
/// -0.017333984, -2.25, -7.7089844, -0.00004425831, -0.40625, -24576.0, -37249.0, \
/// -1.1991882, -32.085938, -0.4375, -0.0012359619, -1536.0, -0.22912993, -0.0015716553, ...]"
/// );
/// ```
#[inline]
pub fn special_random_negative_finite_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
mean_sci_exponent_numerator: u64,
mean_sci_exponent_denominator: u64,
mean_precision_numerator: u64,
mean_precision_denominator: u64,
) -> SpecialRandomNegativeFiniteFloats<T> {
SpecialRandomNegativeFiniteFloats(special_random_positive_finite_primitive_floats(
seed,
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
mean_precision_numerator,
mean_precision_denominator,
))
}
/// Generates nonzero finite primitive floats.
///
/// This `struct` is created by [`special_random_nonzero_finite_primitive_floats`]; see its
/// documentation for more.
#[derive(Clone, Debug)]
pub struct SpecialRandomNonzeroFiniteFloats<T: PrimitiveFloat> {
bs: RandomBools,
xs: SpecialRandomPositiveFiniteFloats<T>,
}
impl<T: PrimitiveFloat> Iterator for SpecialRandomNonzeroFiniteFloats<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
let x = self.xs.next().unwrap();
Some(if self.bs.next().unwrap() { x } else { -x })
}
}
/// Generates finite nonzero primitive floats.
///
/// Simpler floats (those with a lower absolute sci-exponent or precision) are more likely to be
/// chosen. You can specify the mean absolute sci-exponent and precision by passing the numerators
/// and denominators of their means.
///
/// But note that the specified means are only approximate, since the distributions we are sampling
/// are truncated geometric, and their exact means are somewhat annoying to deal with. The
/// practical implications are that
/// - The actual means are slightly lower than the specified means.
/// - However, increasing the specified means increases the actual means, so this still works as a
/// mechanism for controlling the sci-exponent and precision.
/// - The specified sci-exponent mean must be greater than 0 and the precision mean greater than 2,
/// but they may be as high as you like.
///
/// Neither positive not negative zero is generated. `NaN` is not generated either.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::special_random_nonzero_finite_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// special_random_nonzero_finite_primitive_floats::<f32>(EXAMPLE_SEED, 10, 1, 10, 1)
/// .map(NiceFloat),
/// 20
/// ),
/// "[-0.6328125, -9.536743e-7, -0.013671875, 0.6875, -70208.0, 0.01550293, -0.028625488, \
/// -3.3095703, -5.775879, 0.000034958124, 0.4375, 31678.0, -49152.0, -1.0, 49.885254, \
/// -0.40625, -0.0015869141, -1889.5625, -0.14140439, -0.001449585, ...]"
/// );
/// ```
#[inline]
pub fn special_random_nonzero_finite_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
mean_sci_exponent_numerator: u64,
mean_sci_exponent_denominator: u64,
mean_precision_numerator: u64,
mean_precision_denominator: u64,
) -> SpecialRandomNonzeroFiniteFloats<T> {
SpecialRandomNonzeroFiniteFloats {
bs: random_bools(seed.fork("bs")),
xs: special_random_positive_finite_primitive_floats(
seed.fork("xs"),
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
mean_precision_numerator,
mean_precision_denominator,
),
}
}
/// Generates finite primitive floats.
///
/// Simpler floats (those with a lower absolute sci-exponent or precision) are more likely to be
/// chosen. You can specify the numerator and denominator of the probability that a zero will be
/// generated. You can also specify the mean absolute sci-exponent and precision by passing the
/// numerators and denominators of their means of the nonzero floats.
///
/// But note that the specified means are only approximate, since the distributions we are sampling
/// are truncated geometric, and their exact means are somewhat annoying to deal with. The
/// practical implications are that
/// - The actual means are slightly lower than the specified means.
/// - However, increasing the specified means increases the actual means, so this still works as a
/// mechanism for controlling the sci-exponent and precision.
/// - The specified sci-exponent mean must be greater than 0 and the precision mean greater than 2,
/// but they may be as high as you like.
///
/// Positive and negative zero are both generated. `NaN` is not.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::basic::floats::PrimitiveFloat;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::special_random_finite_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// special_random_finite_primitive_floats::<f32>(EXAMPLE_SEED, 10, 1, 10, 1, 1, 10)
/// .map(NiceFloat),
/// 20
/// ),
/// "[0.65625, 0.0000014255784, 0.013183594, 0.0, -0.8125, -74240.0, -0.0078125, -0.03060913, \
/// 3.331552, 4.75, -0.000038146973, -0.3125, -27136.0, -0.0, -59392.0, -1.75, -41.1875, 0.0, \
/// 0.30940247, -0.0009765625, ...]"
/// );
/// ```
#[inline]
pub fn special_random_finite_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
mean_sci_exponent_numerator: u64,
mean_sci_exponent_denominator: u64,
mean_precision_numerator: u64,
mean_precision_denominator: u64,
mean_zero_p_numerator: u64,
mean_zero_p_denominator: u64,
) -> WithSpecialValues<SpecialRandomNonzeroFiniteFloats<T>> {
with_special_values(
seed,
vec![T::ZERO, T::NEGATIVE_ZERO],
mean_zero_p_numerator,
mean_zero_p_denominator,
&|seed_2| {
special_random_nonzero_finite_primitive_floats(
seed_2,
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
mean_precision_numerator,
mean_precision_denominator,
)
},
)
}
/// Generates positive primitive floats.
///
/// Simpler floats (those with a lower absolute sci-exponent or precision) are more likely to be
/// chosen. You can specify the numerator and denominator of the probability that positive infinity
/// will be generated. You can also specify the mean absolute sci-exponent and precision by passing
/// the numerators and denominators of their means of the finite floats.
///
/// But note that the specified means are only approximate, since the distributions we are sampling
/// are truncated geometric, and their exact means are somewhat annoying to deal with. The
/// practical implications are that
/// - The actual means are slightly lower than the specified means.
/// - However, increasing the specified means increases the actual means, so this still works as a
/// mechanism for controlling the sci-exponent and precision.
/// - The specified sci-exponent mean must be greater than 0 and the precision mean greater than 2,
/// but they may be as high as you like.
///
/// Positive zero is generated; negative zero is not. `NaN` is not generated either.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::basic::floats::PrimitiveFloat;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::special_random_positive_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// special_random_positive_primitive_floats::<f32>(EXAMPLE_SEED, 10, 1, 10, 1, 1, 10)
/// .map(NiceFloat),
/// 20
/// ),
/// "[0.6328125, 9.536743e-7, 0.013671875, Infinity, 0.6875, 70208.0, 0.01550293, \
/// 0.028625488, 3.3095703, 5.775879, 0.000034958124, 0.4375, 31678.0, Infinity, 49152.0, \
/// 1.0, 49.885254, Infinity, 0.40625, 0.0015869141, ...]"
/// );
/// ```
#[inline]
pub fn special_random_positive_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
mean_sci_exponent_numerator: u64,
mean_sci_exponent_denominator: u64,
mean_precision_numerator: u64,
mean_precision_denominator: u64,
mean_special_p_numerator: u64,
mean_special_p_denominator: u64,
) -> WithSpecialValue<SpecialRandomPositiveFiniteFloats<T>> {
with_special_value(
seed,
T::POSITIVE_INFINITY,
mean_special_p_numerator,
mean_special_p_denominator,
&|seed_2| {
special_random_positive_finite_primitive_floats(
seed_2,
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
mean_precision_numerator,
mean_precision_denominator,
)
},
)
}
/// Generates negative primitive floats.
///
/// Simpler floats (those with a lower absolute sci-exponent or precision) are more likely to be
/// chosen. You can specify the numerator and denominator of the probability that negative infinity
/// will be generated. You can also specify the mean absolute sci-exponent and precision by passing
/// the numerators and denominators of their means of the finite floats.
///
/// But note that the specified means are only approximate, since the distributions we are sampling
/// are truncated geometric, and their exact means are somewhat annoying to deal with. The
/// practical implications are that
/// - The actual means are slightly lower than the specified means.
/// - However, increasing the specified means increases the actual means, so this still works as a
/// mechanism for controlling the sci-exponent and precision.
/// - The specified sci-exponent mean must be greater than 0 and the precision mean greater than 2,
/// but they may be as high as you like.
///
/// Negative zero is generated; positive zero is not. `NaN` is not generated either.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::basic::floats::PrimitiveFloat;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::special_random_negative_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// special_random_negative_primitive_floats::<f32>(EXAMPLE_SEED, 10, 1, 10, 1, 1, 10)
/// .map(NiceFloat),
/// 20
/// ),
/// "[-0.6328125, -9.536743e-7, -0.013671875, -Infinity, -0.6875, -70208.0, -0.01550293, \
/// -0.028625488, -3.3095703, -5.775879, -0.000034958124, -0.4375, -31678.0, -Infinity, \
/// -49152.0, -1.0, -49.885254, -Infinity, -0.40625, -0.0015869141, ...]"
/// );
/// ```
#[inline]
pub fn special_random_negative_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
mean_sci_exponent_numerator: u64,
mean_sci_exponent_denominator: u64,
mean_precision_numerator: u64,
mean_precision_denominator: u64,
mean_special_p_numerator: u64,
mean_special_p_denominator: u64,
) -> WithSpecialValue<SpecialRandomNegativeFiniteFloats<T>> {
with_special_value(
seed,
T::NEGATIVE_INFINITY,
mean_special_p_numerator,
mean_special_p_denominator,
&|seed_2| {
special_random_negative_finite_primitive_floats(
seed_2,
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
mean_precision_numerator,
mean_precision_denominator,
)
},
)
}
/// Generates nonzero primitive floats.
///
/// Simpler floats (those with a lower absolute sci-exponent or precision) are more likely to be
/// chosen. You can specify the numerator and denominator of the probability that an infinity will
/// be generated. You can also specify the mean absolute sci-exponent and precision by passing the
/// numerators and denominators of their means of the finite floats.
///
/// But note that the specified means are only approximate, since the distributions we are sampling
/// are truncated geometric, and their exact means are somewhat annoying to deal with. The
/// practical implications are that
/// - The actual means are slightly lower than the specified means.
/// - However, increasing the specified means increases the actual means, so this still works as a
/// mechanism for controlling the sci-exponent and precision.
/// - The specified sci-exponent mean must be greater than 0 and the precision mean greater than 2,
/// but they may be as high as you like.
///
/// Neither negative not positive zero is generated. `NaN` is not generated either.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::basic::floats::PrimitiveFloat;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::special_random_nonzero_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// special_random_nonzero_primitive_floats::<f32>(EXAMPLE_SEED, 10, 1, 10, 1, 1, 10)
/// .map(NiceFloat),
/// 20
/// ),
/// "[0.65625, 0.0000014255784, 0.013183594, Infinity, -0.8125, -74240.0, -0.0078125, \
/// -0.03060913, 3.331552, 4.75, -0.000038146973, -0.3125, -27136.0, -Infinity, -59392.0, \
/// -1.75, -41.1875, Infinity, 0.30940247, -0.0009765625, ...]"
/// );
/// ```
#[inline]
pub fn special_random_nonzero_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
mean_sci_exponent_numerator: u64,
mean_sci_exponent_denominator: u64,
mean_precision_numerator: u64,
mean_precision_denominator: u64,
mean_special_p_numerator: u64,
mean_special_p_denominator: u64,
) -> WithSpecialValues<SpecialRandomNonzeroFiniteFloats<T>> {
with_special_values(
seed,
vec![T::POSITIVE_INFINITY, T::NEGATIVE_INFINITY],
mean_special_p_numerator,
mean_special_p_denominator,
&|seed_2| {
special_random_nonzero_finite_primitive_floats(
seed_2,
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
mean_precision_numerator,
mean_precision_denominator,
)
},
)
}
/// Generates primitive floats.
///
/// Simpler floats (those with a lower absolute sci-exponent or precision) are more likely to be
/// chosen. You can specify the numerator and denominator of the probability that zero, infinity,
/// or NaN will be generated. You can also specify the mean absolute sci-exponent and precision by
/// passing the numerators and denominators of their means of the finite floats.
///
/// But note that the specified means are only approximate, since the distributions we are sampling
/// are truncated geometric, and their exact means are somewhat annoying to deal with. The
/// practical implications are that
/// - The actual means are slightly lower than the specified means.
/// - However, increasing the specified means increases the actual means, so this still works as a
/// mechanism for controlling the sci-exponent and precision.
/// - The specified sci-exponent mean must be greater than 0 and the precision mean greater than 2,
/// but they may be as high as you like.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::iterators::prefix_to_string;
/// use malachite_base::num::basic::floats::PrimitiveFloat;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::num::random::special_random_primitive_floats;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
/// prefix_to_string(
/// special_random_primitive_floats::<f32>(EXAMPLE_SEED, 10, 1, 10, 1, 1, 10)
/// .map(NiceFloat),
/// 20
/// ),
/// "[0.65625, 0.0000014255784, 0.013183594, Infinity, -0.8125, -74240.0, -0.0078125, \
/// -0.03060913, 3.331552, 4.75, -0.000038146973, -0.3125, -27136.0, Infinity, -59392.0, \
/// -1.75, -41.1875, Infinity, 0.30940247, -0.0009765625, ...]"
/// );
/// ```
#[inline]
pub fn special_random_primitive_floats<T: PrimitiveFloat>(
seed: Seed,
mean_sci_exponent_numerator: u64,
mean_sci_exponent_denominator: u64,
mean_precision_numerator: u64,
mean_precision_denominator: u64,
mean_special_p_numerator: u64,
mean_special_p_denominator: u64,
) -> WithSpecialValues<SpecialRandomNonzeroFiniteFloats<T>> {
with_special_values(
seed,
vec![T::ZERO, T::NEGATIVE_ZERO, T::POSITIVE_INFINITY, T::NEGATIVE_INFINITY, T::NAN],
mean_special_p_numerator,
mean_special_p_denominator,
&|seed_2| {
special_random_nonzero_finite_primitive_floats(
seed_2,
mean_sci_exponent_numerator,
mean_sci_exponent_denominator,
mean_precision_numerator,
mean_precision_denominator,
)
},
)
}
// normalized sci_exponent and raw mantissas in input, adjusted sci_exponent and mantissas in output
fn mantissas_inclusive<T: PrimitiveFloat>(
mut sci_exponent: i64,
mut am: u64,
mut bm: u64,
precision: u64,
) -> Option<(i64, u64, u64)> {
assert_ne!(precision, 0);
let p: u64 = if sci_exponent < T::MIN_NORMAL_EXPONENT {
let ab = am.significant_bits();
let bb = bm.significant_bits();
assert_eq!(ab, bb);
ab - precision
} else {
am.set_bit(T::MANTISSA_WIDTH);
bm.set_bit(T::MANTISSA_WIDTH);
T::MANTISSA_WIDTH + 1 - precision
};
let mut lo = am.shr_round(p, RoundingMode::Up);
if lo.even() {
lo += 1;
}
let mut hi = bm.shr_round(p, RoundingMode::Down);
if hi == 0 {
return None;
} else if hi.even() {
hi -= 1;
}
if sci_exponent >= T::MIN_NORMAL_EXPONENT {
sci_exponent -= i64::wrapping_from(T::MANTISSA_WIDTH);
}
sci_exponent += i64::wrapping_from(p);
if lo > hi {
None
} else {
Some((sci_exponent, lo >> 1, hi >> 1))
}
}
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct SpecialRandomPositiveFiniteFloatInclusiveRange<T: PrimitiveFloat> {
phantom: PhantomData<*const T>,
am: u64, // raw mantissa
bm: u64,
ae: i64, // sci_exponent
be: i64,
sci_exponents: GeometricRandomSignedRange<i64>,
precision_range_map: HashMap<i64, Vec<(i64, u64, u64)>>,
precision_indices: GeometricRandomNaturalValues<usize>,
ranges: VariableRangeGenerator,
}
impl<T: PrimitiveFloat> Iterator for SpecialRandomPositiveFiniteFloatInclusiveRange<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
let sci_exponent = self.sci_exponents.next().unwrap();
let ae = self.ae;
let be = self.be;
let am = self.am;
let bm = self.bm;
let precision_ranges = self
.precision_range_map
.entry(sci_exponent)
.or_insert_with(|| {
let am = if sci_exponent == ae {
am
} else {
T::from_integer_mantissa_and_exponent(1, sci_exponent)
.unwrap()
.raw_mantissa()
};
let bm = if sci_exponent == be {
bm
} else {
T::from_integer_mantissa_and_exponent(1, sci_exponent + 1)
.unwrap()
.next_lower()
.raw_mantissa()
};
(1..=T::max_precision_for_sci_exponent(sci_exponent))
.filter_map(|p| mantissas_inclusive::<T>(sci_exponent, am, bm, p))
.collect_vec()
});
assert!(!precision_ranges.is_empty());
let i = self.precision_indices.next().unwrap() % precision_ranges.len();
let t = precision_ranges[i];
let mantissa = (self.ranges.next_in_inclusive_range(t.1, t.2) << 1) | 1;
Some(T::from_integer_mantissa_and_exponent(mantissa, t.0).unwrap())
}