nalgebra/tests/core/helper.rs

57 lines
1.5 KiB
Rust
Raw Permalink Normal View History

// This module implement several methods to fill some
// missing features of num-complex when it comes to randomness.
2020-04-06 00:49:48 +08:00
use na::RealField;
use num_complex::Complex;
use quickcheck::{Arbitrary, Gen};
2020-04-06 00:49:48 +08:00
use rand::distributions::{Distribution, Standard};
use rand::Rng;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2021-04-11 17:00:38 +08:00
pub struct RandComplex<T>(pub Complex<T>);
2021-04-11 17:00:38 +08:00
impl<T: Arbitrary + RealField> Arbitrary for RandComplex<T> {
#[inline]
2021-03-01 00:52:14 +08:00
fn arbitrary(rng: &mut Gen) -> Self {
let im = Arbitrary::arbitrary(rng);
let re = Arbitrary::arbitrary(rng);
RandComplex(Complex::new(re, im))
}
}
2021-04-11 17:00:38 +08:00
impl<T: RealField> Distribution<RandComplex<T>> for Standard
2020-04-06 00:49:48 +08:00
where
2021-04-11 17:00:38 +08:00
Standard: Distribution<T>,
{
#[inline]
2021-04-11 17:00:38 +08:00
fn sample<'a, G: Rng + ?Sized>(&self, rng: &'a mut G) -> RandComplex<T> {
let re = rng.gen();
let im = rng.gen();
RandComplex(Complex::new(re, im))
}
}
// This is a wrapper similar to RandComplex, but for non-complex.
// This exists only to make generic tests easier to write.
//
// Generates variates in the range [0, 1).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2021-04-11 17:00:38 +08:00
pub struct RandScalar<T>(pub T);
2021-04-11 17:00:38 +08:00
impl<T: Arbitrary> Arbitrary for RandScalar<T> {
#[inline]
2021-03-01 00:52:14 +08:00
fn arbitrary(rng: &mut Gen) -> Self {
RandScalar(Arbitrary::arbitrary(rng))
}
}
2021-04-11 17:00:38 +08:00
impl<T: RealField> Distribution<RandScalar<T>> for Standard
2020-04-06 00:49:48 +08:00
where
2021-04-11 17:00:38 +08:00
Standard: Distribution<T>,
{
#[inline]
2021-04-11 17:00:38 +08:00
fn sample<'a, G: Rng + ?Sized>(&self, rng: &'a mut G) -> RandScalar<T> {
RandScalar(self.sample(rng))
}
2020-04-06 00:49:48 +08:00
}