|
| 1 | +//! Random module. |
| 2 | +
|
| 3 | +extern crate rand; |
| 4 | + |
| 5 | +use super::super::obj::{objfloat, objtype}; |
| 6 | +use super::super::pyobject::{ |
| 7 | + DictProtocol, PyContext, PyFuncArgs, PyObjectRef, PyResult, TypeProtocol, |
| 8 | +}; |
| 9 | +use super::super::VirtualMachine; |
| 10 | +use stdlib::random::rand::distributions::{Distribution, Normal}; |
| 11 | + |
| 12 | +pub fn mk_module(ctx: &PyContext) -> PyObjectRef { |
| 13 | + let py_mod = ctx.new_module(&"random".to_string(), ctx.new_scope(None)); |
| 14 | + py_mod.set_item("gauss", ctx.new_rustfunc(random_gauss)); |
| 15 | + py_mod.set_item("normalvariate", ctx.new_rustfunc(random_normalvariate)); |
| 16 | + py_mod.set_item("random", ctx.new_rustfunc(random_random)); |
| 17 | + // py_mod.set_item("weibull", ctx.new_rustfunc(random_weibullvariate)); |
| 18 | + // TODO: implement more random functions. |
| 19 | + py_mod |
| 20 | +} |
| 21 | + |
| 22 | +fn random_gauss(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { |
| 23 | + // TODO: is this the same? |
| 24 | + random_normalvariate(vm, args) |
| 25 | +} |
| 26 | + |
| 27 | +fn random_normalvariate(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { |
| 28 | + arg_check!( |
| 29 | + vm, |
| 30 | + args, |
| 31 | + required = [ |
| 32 | + (mu, Some(vm.ctx.float_type())), |
| 33 | + (sigma, Some(vm.ctx.float_type())) |
| 34 | + ] |
| 35 | + ); |
| 36 | + let mu = objfloat::get_value(mu); |
| 37 | + let sigma = objfloat::get_value(sigma); |
| 38 | + let normal = Normal::new(mu, sigma); |
| 39 | + let value = normal.sample(&mut rand::thread_rng()); |
| 40 | + let py_value = vm.ctx.new_float(value); |
| 41 | + Ok(py_value) |
| 42 | +} |
| 43 | + |
| 44 | +fn random_random(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { |
| 45 | + arg_check!(vm, args); |
| 46 | + let value = rand::random::<f64>(); |
| 47 | + let py_value = vm.ctx.new_float(value); |
| 48 | + Ok(py_value) |
| 49 | +} |
| 50 | + |
| 51 | +/* |
| 52 | + * TODO: enable this function: |
| 53 | +fn random_weibullvariate(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { |
| 54 | + arg_check!(vm, args, required = [(alpha, Some(vm.ctx.float_type())), (beta, Some(vm.ctx.float_type()))]); |
| 55 | + let alpha = objfloat::get_value(alpha); |
| 56 | + let beta = objfloat::get_value(beta); |
| 57 | + let weibull = Weibull::new(alpha, beta); |
| 58 | + let value = weibull.sample(&mut rand::thread_rng()); |
| 59 | + let py_value = vm.ctx.new_float(value); |
| 60 | + Ok(py_value) |
| 61 | +} |
| 62 | +*/ |
0 commit comments