1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
//! Mathematical transformation operations (sqrt, recip, pow)
#[allow(unused_imports)]
use crate::backends::VectorBackend;
use crate::dispatch_unary_op;
use crate::{Result, Vector};
impl Vector<f32> {
/// Element-wise square root: result\[i\] = sqrt(self\[i\])
///
/// Computes the square root of each element. For negative values, returns NaN
/// following IEEE 754 floating-point semantics.
///
/// # Returns
///
/// A new vector where each element is the square root of the corresponding input element
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use trueno::Vector;
///
/// let a = Vector::from_slice(&[4.0, 9.0, 16.0, 25.0]);
/// let result = a.sqrt()?;
/// assert_eq!(result.as_slice(), &[2.0, 3.0, 4.0, 5.0]);
/// # Ok(())
/// # }
/// ```
///
/// Negative values produce NaN:
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use trueno::Vector;
///
/// let a = Vector::from_slice(&[-1.0, 4.0]);
/// let result = a.sqrt()?;
/// assert!(result.as_slice()[0].is_nan());
/// assert_eq!(result.as_slice()[1], 2.0);
/// # Ok(())
/// # }
/// ```
///
/// # Use Cases
///
/// - Distance calculations: Euclidean distance computation
/// - Statistics: Standard deviation, RMS (root mean square)
/// - Machine learning: Normalization, gradient descent with adaptive learning rates
/// - Signal processing: Amplitude calculations, power spectrum analysis
/// - Physics simulations: Velocity from kinetic energy, wave propagation
pub fn sqrt(&self) -> Result<Vector<f32>> {
// Uninit allocation: dispatch_unary_op!(sqrt) writes every element.
let n = self.len();
let mut result_data: Vec<f32> = Vec::with_capacity(n);
// SAFETY: dispatch_unary_op writes result_data[i] = sqrt(input[i]) for all i.
unsafe {
result_data.set_len(n);
}
if !self.as_slice().is_empty() {
// Use parallel processing for large arrays
#[cfg(feature = "parallel")]
{
const PARALLEL_THRESHOLD: usize = 100_000;
const CHUNK_SIZE: usize = 65536;
if self.len() >= PARALLEL_THRESHOLD {
use rayon::prelude::*;
self.as_slice()
.par_chunks(CHUNK_SIZE)
.zip(result_data.par_chunks_mut(CHUNK_SIZE))
.for_each(|(chunk_in, chunk_out)| {
dispatch_unary_op!(self.backend(), sqrt, chunk_in, chunk_out);
});
return Ok(Vector { data: result_data, backend: self.backend() });
}
}
dispatch_unary_op!(self.backend(), sqrt, self.as_slice(), &mut result_data);
}
Ok(Vector { data: result_data, backend: self.backend() })
}
/// Element-wise reciprocal: result\[i\] = 1 / self\[i\]
///
/// Computes the reciprocal (multiplicative inverse) of each element.
/// For zero values, returns infinity following IEEE 754 floating-point semantics.
///
/// # Returns
///
/// A new vector where each element is the reciprocal of the corresponding input element
///
/// # Examples
///
/// ```
/// use trueno::Vector;
///
/// let a = Vector::from_slice(&[2.0, 4.0, 5.0, 10.0]);
/// let result = a.recip().unwrap();
/// assert_eq!(result.as_slice(), &[0.5, 0.25, 0.2, 0.1]);
/// ```
///
/// Zero values produce infinity:
/// ```
/// use trueno::Vector;
///
/// let a = Vector::from_slice(&[0.0, 2.0]);
/// let result = a.recip().unwrap();
/// assert!(result.as_slice()[0].is_infinite());
/// assert_eq!(result.as_slice()[1], 0.5);
/// ```
///
/// # Use Cases
///
/// - Division optimization: `a / b` -> `a * recip(b)` (multiplication is faster)
/// - Neural networks: Learning rate schedules, weight normalization
/// - Statistics: Harmonic mean calculations, inverse transformations
/// - Physics: Resistance (R = 1/G), optical power (P = 1/f)
/// - Signal processing: Frequency to period conversion, filter design
pub fn recip(&self) -> Result<Vector<f32>> {
// Uninit allocation: dispatch_unary_op!(recip) writes every element.
let n = self.len();
let mut result_data: Vec<f32> = Vec::with_capacity(n);
// SAFETY: dispatch_unary_op writes result_data[i] = 1/input[i] for all i.
unsafe {
result_data.set_len(n);
}
if !self.as_slice().is_empty() {
dispatch_unary_op!(self.backend(), recip, self.as_slice(), &mut result_data);
}
Ok(Vector { data: result_data, backend: self.backend() })
}
/// Element-wise power: result\[i\] = base\[i\]^n
///
/// Raises each element to the given power `n`.
/// Uses Rust's optimized f32::powf() method.
///
/// # Examples
///
/// ```
/// use trueno::Vector;
///
/// let v = Vector::from_slice(&[2.0, 3.0, 4.0]);
/// let squared = v.pow(2.0).unwrap();
/// assert_eq!(squared.as_slice(), &[4.0, 9.0, 16.0]);
///
/// let sqrt = v.pow(0.5).unwrap(); // Fractional power = root
/// ```
///
/// # Special Cases
///
/// - `x.pow(0.0)` returns 1.0 for all x (even x=0)
/// - `x.pow(1.0)` returns x (identity)
/// - `x.pow(-1.0)` returns 1/x (reciprocal)
/// - `x.pow(0.5)` returns sqrt(x) (square root)
///
/// # Applications
///
/// - Statistics: Power transformations (Box-Cox, Yeo-Johnson)
/// - Machine learning: Polynomial features, activation functions
/// - Physics: Inverse square law (1/r^2), power laws
/// - Signal processing: Power spectral density, root mean square
pub fn pow(&self, n: f32) -> Result<Vector<f32>> {
let pow_data: Vec<f32> = self.as_slice().iter().map(|x| x.powf(n)).collect();
Ok(Vector::from_vec(pow_data))
}
}