1use crate::vector::{Dot, Vector};
2
3use std::{
4 fmt,
5 ops::{Index, IndexMut},
6};
7
8#[derive(Clone)]
10pub struct VectorF {
11 coefficients: Vec<f64>,
13
14 dimension: usize,
16}
17
18impl Vector for VectorF {
19 fn basis_vector(&self, position: usize) -> Self {
20 assert!(position < self.dimension());
21
22 let mut coefficients = vec![0.0; self.dimension()];
23 coefficients[position] = 1.0;
24
25 Self {
26 coefficients,
27 dimension: self.dimension(),
28 }
29 }
30
31 fn init(dimension: usize) -> Self {
32 Self {
33 coefficients: vec![Default::default(); dimension],
34 dimension,
35 }
36 }
37
38 fn dimension(&self) -> usize {
39 self.dimension
40 }
41
42 fn add(&self, other: &Self) -> Self {
43 let n = self.dimension();
44
45 assert_eq!(n, other.dimension());
46
47 Self::from_vector(
48 (0..n)
49 .map(|i| self.coefficients[i] + other.coefficients[i])
50 .collect(),
51 )
52 }
53
54 fn sub(&self, other: &Self) -> Self {
55 let n = self.dimension();
56
57 assert_eq!(n, other.dimension());
58
59 Self::from_vector(
60 (0..n)
61 .map(|i| self.coefficients[i] - other.coefficients[i])
62 .collect(),
63 )
64 }
65}
66
67impl Dot<f64> for VectorF {
68 fn dot(&self, other: &Self) -> f64 {
69 let n = self.dimension();
70 assert_eq!(n, other.dimension());
71
72 (0..n)
73 .map(|i| self.coefficients[i] * other.coefficients[i])
74 .sum()
75 }
76}
77
78impl VectorF {
79 pub fn from_vector(coefficients: Vec<f64>) -> Self {
81 Self {
82 dimension: coefficients.len(),
83 coefficients,
84 }
85 }
86
87 pub fn mulf(&self, other: f64) -> Self {
89 let n = self.dimension();
90
91 Self::from_vector((0..n).map(|i| self.coefficients[i] * other).collect())
92 }
93}
94
95impl Index<usize> for VectorF {
96 type Output = f64;
97
98 fn index(&self, index: usize) -> &f64 {
99 &self.coefficients[index]
100 }
101}
102
103impl IndexMut<usize> for VectorF {
104 fn index_mut(&mut self, index: usize) -> &mut f64 {
105 &mut self.coefficients[index]
106 }
107}
108
109impl fmt::Debug for VectorF {
110 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
111 write!(f, "{:?}", self.coefficients)
112 }
113}