rmatrix_ks 0.5.4

matrix and some algebra in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! # instances::float
//!
//! Functions and related implementations for single precision floating-point numbers.

use rand::{
    Rng,
    distributions::uniform::{SampleBorrow, SampleUniform, UniformFloat, UniformSampler},
};

use crate::number::{
    instances::{int::Int, integer::Integer, ratio::Rational},
    traits::{
        floating::Floating,
        fractional::Fractional,
        integral::Integral,
        number::Number,
        one::One,
        real::Real,
        realfloat::RealFloat,
        realfrac::RealFrac,
        zero::Zero,
    },
    utils::{from_integral, non_negative_integral_power},
};

/// Float numbers are the wrapper type for f32.
#[derive(Clone, PartialOrd)]
pub struct Float {
    inner: f32,
}

impl Float {
    /// Construct float numbers from f32.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rmatrix_ks::number::instances::float::Float;
    ///
    /// fn main() { let _f = Float::of(12.0); }
    /// ```
    pub const fn of(num: f32) -> Self { Self { inner: num } }

    /// Construct float numbers from string.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rmatrix_ks::number::instances::float::Float;
    ///
    /// fn main() {
    ///     let sf = Float::of_str("-12.0").unwrap();
    ///     let f = Float::of(-12.0);
    ///     assert_eq!(sf, f);
    /// }
    /// ```
    pub fn of_str(float_number: &str) -> Option<Self> {
        std::str::FromStr::from_str(float_number).ok()
    }
}

/// Implement the concept of ZERO for the float number.
impl Zero for Float {
    fn zero() -> Self { Self { inner: 0.0f32 } }

    /// Validate whether a float number is ZERO.
    ///
    /// Use half-precision to avoid certain floating-point precision errors.
    ///
    /// ```rust
    /// use rmatrix_ks::number::{instances::float::Float, traits::zero::Zero};
    ///
    /// fn main() {
    ///     let f = Float::of(core::f32::EPSILON);
    ///     assert!(f.is_zero());
    /// }
    /// ```
    fn is_zero(&self) -> bool { self.inner.abs() <= core::f32::EPSILON.sqrt() }
}

/// Implement the concept of ONE for the float number.
impl One for Float {
    fn one() -> Self { Self { inner: 1.0f32 } }

    fn is_one(&self) -> bool { (self.clone() - Self::one()).is_zero() }
}

/// Implement Default for the float number.
impl std::default::Default for Float {
    fn default() -> Self { Self::zero() }
}

/// Implement the negation operation for the float number.
impl std::ops::Neg for Float {
    type Output = Self;

    fn neg(self) -> Self::Output { Self { inner: -self.inner } }
}

/// Implement the addition operation for the float number.
impl std::ops::Add for Float {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self {
            inner: self.inner + rhs.inner,
        }
    }
}

/// Implement the subtraction operation for the float number.
impl std::ops::Sub for Float {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        Self {
            inner: self.inner - rhs.inner,
        }
    }
}

/// Implement the multiplication operation for the float number.
impl std::ops::Mul for Float {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self::Output {
        Self {
            inner: self.inner * rhs.inner,
        }
    }
}

/// Implement the division operation for the float number.
impl std::ops::Div for Float {
    type Output = Self;

    fn div(self, rhs: Self) -> Self::Output {
        Self {
            inner: self.inner / rhs.inner,
        }
    }
}

/// Implement equality for float numbers.
impl std::cmp::PartialEq for Float {
    fn eq(&self, other: &Self) -> bool { (self.clone() - other.clone()).is_zero() }
}

/// Implement the concept of NUMBER for the float number.
impl Number for Float {
    fn absolute_value(&self) -> Self {
        Self {
            inner: self.inner.abs(),
        }
    }

    fn sign_number(&self) -> Self {
        if self.is_zero() {
            Self::zero()
        } else if self.inner.is_sign_positive() {
            Self::one()
        } else {
            -Self::one()
        }
    }

    /// Construct a float number from an integer.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rmatrix_ks::number::{
    ///     instances::{float::Float, integer::Integer},
    ///     traits::number::Number,
    /// };
    ///
    /// fn main() {
    ///     let i1 = Integer::of_str("123456789").unwrap();
    ///     let f1 = Float::from_integer(i1);
    ///     assert_eq!(f1, Float::of(123456789.0));
    /// }
    /// ```
    ///
    /// ## Warnings
    ///
    /// <div class="warning">
    ///
    /// When the size of an integer exceeds the maximum integer
    /// representable by a single-precision floating-point number,
    /// significant errors may occur.
    ///
    /// ```rust
    /// use rmatrix_ks::number::{
    ///     instances::{float::Float, integer::Integer},
    ///     traits::number::Number,
    /// };
    ///
    /// fn main() {
    ///     let i2 = Integer::of_str("1234567891011121314151617181920").unwrap();
    ///     let f2 = Float::from_integer(i2);
    ///     assert_eq!(f2, Float::of(1234567900000000000000000000000.0));
    /// }
    /// ```
    ///
    /// </div>
    fn from_integer(integer_number: Integer) -> Self {
        if integer_number.is_zero() {
            Self::zero()
        } else {
            let inner = format!("{:?}", integer_number)
                .parse::<f32>()
                .expect(&format!(
                    "Error[Float::from_Integer]: ({}) should be a valid f32 number.",
                    integer_number
                ));
            Self { inner }
        }
    }
}

/// Implement the concept of RealFloat for Float.
impl RealFloat for Float {
    const FLOAT_DIGITS: Int = Int::of(24);
    const FLOAT_RANGE: (Int, Int) = (Int::of(-125), Int::of(128));

    fn is_not_a_number(&self) -> bool { self.inner.is_nan() }

    fn is_infinite_number(&self) -> bool { self.inner.is_infinite() }

    fn is_denormalized(&self) -> bool { self.inner.is_subnormal() }

    fn is_negative_zero(&self) -> bool { self.is_zero() && self.inner.is_sign_negative() }
}

/// Implement the concept of RealFrac for Float.
impl RealFrac for Float {
    fn proper_fraction<I: Integral>(self) -> (I, Self) {
        (
            from_integral(Int::of(self.inner.trunc() as i32)),
            Self::of(self.inner.fract()),
        )
    }
}

/// Implement the concept of Real for Float.
impl Real for Float {
    /// Convert single-precision floating-point number to rational number.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rmatrix_ks::number::{
    ///     instances::{float::Float, ratio::Rational},
    ///     traits::{floating::Floating, real::Real},
    /// };
    ///
    /// fn main() {
    ///     let m = Float::PI;
    ///     let m_rat = m.to_rational();
    ///     let rat_expect = Rational::of_str("13176795 % 4194304").unwrap();
    ///     assert_eq!(m_rat, rat_expect);
    /// }
    /// ```
    fn to_rational(self) -> Rational {
        if self.is_not_a_number() || self.is_infinite_number() {
            panic!(
                "Error[Float::to_rational]: {} is not a valid floating number",
                self
            );
        } else if self.is_zero() {
            Rational {
                numerator: Integer::zero(),
                denominator: Integer::one(),
            }
        } else {
            let (sig, exp) = self.decode_float();
            let denominator =
                non_negative_integral_power(Int::of(2).to_integer(), exp.absolute_value())
                    .expect(concat!(
                        "Error[Float::to_rational]: ",
                        "Failed to compute the denominator via exponentiation."
                    ));
            Rational::of(sig, denominator).refine()
        }
    }
}

/// Implement the concept of Floating for Float.
impl Floating for Float {
    const PI: Self = Self::of(core::f32::consts::PI);
    const ZERO: Self = Self { inner: 0.0f32 };

    fn exponential(self) -> Self {
        Self {
            inner: self.inner.exp(),
        }
    }

    fn logarithmic(self) -> Self {
        Self {
            inner: self.inner.ln(),
        }
    }

    fn sine(self) -> Self {
        Self {
            inner: self.inner.sin(),
        }
    }

    fn cosine(self) -> Self {
        Self {
            inner: self.inner.cos(),
        }
    }

    fn arc_sine(self) -> Self {
        Self {
            inner: self.inner.asin(),
        }
    }

    fn arc_cosine(self) -> Self {
        Self {
            inner: self.inner.acos(),
        }
    }

    fn arc_tangent(self) -> Self {
        Self {
            inner: self.inner.atan(),
        }
    }

    fn hyperbolic_sine(self) -> Self {
        Self {
            inner: self.inner.sinh(),
        }
    }

    fn hyperbolic_cosine(self) -> Self {
        Self {
            inner: self.inner.cosh(),
        }
    }

    fn arc_hyperbolic_sine(self) -> Self {
        Self {
            inner: self.inner.asinh(),
        }
    }

    fn arc_hyperbolic_cosine(self) -> Self {
        Self {
            inner: self.inner.acosh(),
        }
    }

    fn arc_hyperbolic_tangent(self) -> Self {
        Self {
            inner: self.inner.atanh(),
        }
    }
}

/// Implement the concept of Fractional for Float.
impl Fractional for Float {
    fn half() -> Self { Self { inner: 0.5f32 } }

    fn reciprocal(self) -> Self {
        let rational = self.to_rational();
        Self::from_integer(rational.denominator) / Self::from_integer(rational.numerator)
    }

    fn from_rational(rational_number: Rational) -> Self {
        Self::from_integer(rational_number.numerator)
            / Self::from_integer(rational_number.denominator)
    }
}

/// Implement Display for Float.
impl std::fmt::Display for Float {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.inner)
    }
}

/// Implement Debug for Float.
impl std::fmt::Debug for Float {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:+}", self.inner)
    }
}

/// Implement FromStr for Float.
impl std::str::FromStr for Float {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let trimmed_s = s.trim();
        if let Ok(num) = trimmed_s.parse::<f32>() {
            Ok(Self { inner: num })
        } else {
            eprintln!(
                "Error[Float::from_str]: ({}) is not a valid Float literal.",
                trimmed_s
            );
            Err(())
        }
    }
}

/// Uniform distribution of float numbers.
pub struct UniformF32(UniformFloat<f32>);

/// Implement uniform sampling for the uniform distribution of float numbers.
impl UniformSampler for UniformF32 {
    type X = Float;

    fn new<B1, B2>(low: B1, high: B2) -> Self
    where
        B1: SampleBorrow<Self::X> + Sized,
        B2: SampleBorrow<Self::X> + Sized,
    {
        Self(UniformFloat::<f32>::new(
            low.borrow().inner,
            high.borrow().inner,
        ))
    }

    fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self
    where
        B1: SampleBorrow<Self::X> + Sized,
        B2: SampleBorrow<Self::X> + Sized,
    {
        Self(UniformFloat::<f32>::new_inclusive(
            low.borrow().inner,
            high.borrow().inner,
        ))
    }

    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
        Self::X::of(self.0.sample(rng))
    }
}

/// Implement uniform sampling for float numbers.
impl SampleUniform for Float {
    type Sampler = UniformF32;
}