修复连续采集时没有时间间隔导致通讯失败从而导致无有法正常连续采集的问题 修改如下
This commit is contained in:
@ -128,7 +128,51 @@ fn read_csv_to_vec(file_path: &str) -> Result<Vec<f64>, Box<dyn Error>> {
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
use nalgebra::{DMatrix, DVector};
|
||||
|
||||
pub fn compute_weave_coeff(x_data:Vec<f64>,y_data:Vec<f64>)->Vec<f64>{
|
||||
|
||||
assert_eq!(x_data.len(), y_data.len());
|
||||
|
||||
let n = x_data.len();
|
||||
|
||||
// 构建设计矩阵 X 和观测向量 y
|
||||
let mut x_matrix = DMatrix::zeros(n, 4); // 三阶多项式有 4 个系数
|
||||
let mut y_vector = DVector::from_vec(y_data.clone());
|
||||
|
||||
for (i, &x) in x_data.iter().enumerate() {
|
||||
x_matrix[(i, 0)] = 1.0; // 常数项
|
||||
x_matrix[(i, 1)] = x; // x
|
||||
x_matrix[(i, 2)] = x.powi(2); // x²
|
||||
x_matrix[(i, 3)] = x.powi(3); // x³
|
||||
}
|
||||
|
||||
// 使用正规方程求解最小二乘问题: (XᵀX)β = Xᵀy
|
||||
let xt = x_matrix.transpose();
|
||||
let xtx = &xt * &x_matrix;
|
||||
let xty = &xt * &y_vector;
|
||||
|
||||
// 求解方程 (XᵀX)β = Xᵀy
|
||||
let beta = xtx
|
||||
.lu()
|
||||
.solve(&xty)
|
||||
.expect("无法求解正规方程,可能是矩阵奇异");
|
||||
|
||||
// 输出拟合系数
|
||||
println!("拟合的三阶多项式系数:");
|
||||
println!("y = {:.4} + {:.4}x + {:.4}x² + {:.4}x³", beta[0], beta[1], beta[2], beta[3]);
|
||||
|
||||
// 示例:使用拟合的多项式进行预测
|
||||
let x_test = 6.0;
|
||||
let y_pred = beta[0] + beta[1]*x_test + beta[2]*x_test.powi(2) + beta[3]*x_test.powi(3);
|
||||
println!("对于 x = {:.2}, 预测的 y = {:.4}", x_test, y_pred);
|
||||
let mut retvec=Vec::new();
|
||||
for i in 0..4{
|
||||
retvec.push(beta[i]);
|
||||
}
|
||||
retvec
|
||||
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_find_peek(){
|
||||
|
||||
Reference in New Issue
Block a user