use num::{Float, FromPrimitive};
use std::f64::consts::PI;
use std::iter::Sum;
pub fn rastrigin<T: Float + FromPrimitive + Sum>(param: &[T]) -> T {
rastrigin_a(param, T::from_f64(10.0).unwrap())
}
pub fn rastrigin_a<T: Float + FromPrimitive + Sum>(param: &[T], a: T) -> T {
a * T::from_usize(param.len()).unwrap()
+ param
.iter()
.map(|&x| x.powi(2) - a * (T::from_f64(2.0 * PI).unwrap() * x).cos())
.sum()
}
mod tests {
#[test]
fn test_rastrigin_optimum() {
assert!(::rastrigin(&[0.0_f32, 0.0_f32]).abs() < ::std::f32::EPSILON);
assert!(::rastrigin(&[0.0_f64, 0.0_f64]).abs() < ::std::f64::EPSILON);
}
#[test]
fn test_parameter_a() {
assert!(
::rastrigin(&[0.0_f32, 0.0_f32]).abs()
== ::rastrigin_a(&[0.0_f32, 0.0_f32], 10.0).abs()
);
}
}