peroxide/structure/
multinomial.rs1#[allow(unused_imports)]
2use crate::structure::matrix::*;
3use crate::traits::math::InnerProduct;
4use crate::util::useful::*;
5use std::fmt;
6
7#[derive(Debug, Clone)]
8pub struct Multinomial {
9 coef: Vec<f64>,
10}
11
12impl fmt::Display for Multinomial {
13 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
14 let mut result = String::new();
15 let l = self.coef.len();
16
17 if l == 1 {
18 let value = self.coef[0];
19 let target = choose_shorter_string(format!("{}x_0", value), format!("{:.4}x_0", value));
20 return write!(f, "{}", target);
21 }
22
23 let first_value = self.coef[0];
24 result.push_str(&choose_shorter_string(
25 format!("{}x_0", first_value),
26 format!("{:.4}x_0", first_value),
27 ));
28
29 for i in 1..l {
30 let value = self.coef[i];
31 if value > 0. {
32 let target = choose_shorter_string(
33 format!(" + {}x_{}", value, i),
34 format!(" + {:.4}x_{}", value, i),
35 );
36 result.push_str(&target);
37 } else if value < 0. {
38 let target = choose_shorter_string(
39 format!(" - {}x_{}", value, i),
40 format!(" - {:.4}x_{}", value, i),
41 );
42 result.push_str(&target);
43 }
44 }
45 write!(f, "{}", result)
46 }
47}
48
49impl Multinomial {
50 pub fn new(coef: Vec<f64>) -> Self {
51 Self { coef }
52 }
53
54 pub fn eval(&self, values: &Vec<f64>) -> f64 {
55 self.coef.dot(values)
56 }
57}