C语言 最小二乘 向量旋转 欧拉方法求洛伦兹方程

本文介绍了一个用于最小二乘线性拟合的C程序,包括数据读取、拟合及结果输出等功能。此外,还探讨了向量旋转及洛伦兹方程的数值解法。

最小二乘

This question will develop a set of functions to least square fit the linear model 𝑦=𝑘𝑥+𝑞 to arbitrary data provided in an input file, i.e. identify the coefficients 𝑘 and 𝑞 to optimally overlap the data points (𝑥, 𝑦) available in the input file.
本问题将开发一套函数,对输入文件中的任意数据进行线性模型𝑦=𝑘𝑥+𝑞的最小二乘拟合,即识别出系数𝑘和𝑞,使输入文件中可获得的数据点(𝑥,𝑦)最优重叠。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
   
   
    char *filename;
    int num_points;
    double *x;
    double *y;
} data;
typedef struct {
   
   
double k;
double q;
double r2;
} fitcoef;
/*   4-4    */
int data_size(char filename[]){
   
   
    FILE *fp = NULL;
    int ans=0;
    double x,y;
    fp = fopen(filename, "r");
    if(fp == NULL){
   
   
        return -1;
    }
    while(fscanf(fp,"%lf %lf",&x,&y)!=EOF){
   
   
        ans++;
    }
    fclose(fp);
    return ans;
}
/*   4-5    */
int data_read(data* m_data){
   
   
    FILE *fp = NULL;
    int idx=0;
    m_data->x=(double*) malloc((m_data->num_points)*sizeof(double));
    m_data->y=(double*) malloc((m_data->num_points)*sizeof(double));
    fp = fopen(m_data->filename, "r");
    if(fp == NULL){
   
   
        return -1;
    }
    for(int i=0;i<m_data->num_points;i++){
   
   
        fscanf(fp,"%lf %lf",&(m_data->x[idx]),&(m_data->y[idx]));
        idx++;
    }
    fclose(fp);
    return 0;
}
/*   4-6    */
fitcoef linear_fit(data* m_data){
   
   
    fitcoef ans;
    double _x = 0.0, _y = 0.0;
    double s_xx = 0.0, s_yy = 0.0, s_yx = 0.0;
    for(int i=0;i<m_data->num_points;i++){
   
   
        _x+=m_data->x[i];
        _y+=m_data->y[i];
    }
    _x/=m_data->num_points;
    _y/=m_data->num_points;
    for(int i=0;i<m_data->num_points;i++){
   
   
        s_xx+=pow(m_data->x[i] - _x,2.0);
    }
    s_xx/=m_data->num_points;
    for (int i = 0; i < m_data->num_points; i++) {
   
   
        s_yy += pow((m_data->y[i] - _y),2.0) ;
    }
    s_yy/=m_data->num_points;
    for (int i = 0; i < m_data->num_points; i++) {
   
   
        s_yx += (m_data->x[i] - _x) * (m_data->y[i] - _y);
    }
    s_yx/=m_data->num_points;
    ans.k=s_yx/s_xx;
    ans.q=_y-ans.k*_x;
    ans.r2=s_yx*s_yx/s_xx/s_yy;
    return ans;
}
/*   4-7    */
void print_data(data* m_data){
   
   
    printf("\nData file: %s\n", m_data->filename);
    printf("Number of data points: %m_data\n\n", m_data->num_points   );
    printf(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清欢_小铭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值