-
Notifications
You must be signed in to change notification settings - Fork 432
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
gen_iter()
for distributions?
#58
Comments
In my case, I'd like to have (0..).map(|_| rng.gen_range(low, high))...; |
What you're asking would be encompassed by my feature request. You could have a uniform distribution with the specified minimum and maximum value, and then run |
Oh, certainly. I was just dropping that little snippet as a way for future people to get something today, but also adding an implicit +1. |
Please see #275 which I think implements what was asked here. As pointed out it's not really necessary so we need to decide what to do here. |
But @burdges came up with a method that me be useful:
|
Would adding an iterator method to the distribution trait like this have disadvantages? pub trait Distribution<T> {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T;
fn iter<'r, R: Rng>(self, rng: &'r mut R) -> DistIter<'r, Self, R, T>
where Self: Sized
{
DistIter {
distr: self,
rng: rng,
phantom: ::core::marker::PhantomData,
}
}
}
#[derive(Debug)]
pub struct DistIter<'a, D, R, T> where D: Distribution<T>, R: Rng + 'a {
distr: D,
rng: &'a mut R,
phantom: ::core::marker::PhantomData<T>,
}
impl<'a, D, R, T> Iterator for DistIter<'a, D, R, T>
where D: Distribution<T>, R: Rng + 'a
{
type Item = T;
fn next(&mut self) -> Option<T> {
Some(self.rng.sample(&self.distr))
}
} It can be used like this: use distributions::Normal;
let mut rng = thread_rng();
let distr = Normal::new(10.0, 10.0);
let results: Vec<_> = distr.iter(&mut rng).take(100).collect(); |
Sounds good, but we probably don't want both |
I don't think there is a real difference, as both need the same arguments and both would produce the same sort of iterator. |
Now available as |
The
Rng
trait has thegen_iter()
function which creates an iterator producing an infinite numbers of random numbers. It is then easy to manipulate the the iterator and generate vectors of random numbers.Is there a reason why the various distributions do not implement this? In my particular case, I am needing to create vectors of numbers distributed normally and there is no easy way of doing that. One can't use
vec![normal.ind_sample(rng); len];
because it evaluates the function once and then clones the result.I am quite happy to implement this in this crate (if people are interested). I was thinking of maybe adding
gen_iter<R: Rng>(&mut self, rng: &mut R)
andgen_ind_iter<R: Rng>(&mut self, rng: &mut R)
underSample
andIndependentSample
respectively.The text was updated successfully, but these errors were encountered: