|
发表于 2024-1-29 10:34:43
|
显示全部楼层
STM32和电脑跑C有什么区别?是不支持浮点?还是内存不够?还是CPU速度不行?
如果这些没区别,你没有必要强调STM32。你需要的是C的拟合代码。
User
I have x = 1,2,3,4,5,6,7,8,9,10,11, and y = 0.01,1.1,2.77,4.3,5.68,6.87,7. 88,8.7,9.34,9. 85,10.21
I need linear regression code in C
Certainly! Here's the C code for linear regression using the given data:
c
- #include <stdio.h>
- // Function to calculate the mean of an array
- float calculateMean(float arr[], int n) {
- float sum = 0.0;
- for (int i = 0; i < n; i++) {
- sum += arr[i];
- }
- return sum / n;
- }
- // Function to calculate the slope (m) of the line
- float calculateSlope(float x[], float y[], int n) {
- float sumXY = 0.0, sumX = 0.0, sumY = 0.0, sumX2 = 0.0;
- for (int i = 0; i < n; i++) {
- sumXY += x[i] * y[i];
- sumX += x[i];
- sumY += y[i];
- sumX2 += x[i] * x[i];
- }
- return (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
- }
- // Function to calculate the intercept (c) of the line
- float calculateIntercept(float x[], float y[], int n, float slope) {
- float meanX = calculateMean(x, n);
- float meanY = calculateMean(y, n);
- return meanY - slope * meanX;
- }
- int main() {
- // Given data
- float x[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
- float y[] = {0.01, 1.1, 2.77, 4.3, 5.68, 6.87, 7.88, 8.7, 9.34, 9.85, 10.21};
- // Number of data points
- int n = sizeof(x) / sizeof(x[0]);
- // Calculate slope and intercept
- float slope = calculateSlope(x, y, n);
- float intercept = calculateIntercept(x, y, n, slope);
- // Print the equation of the line (y = mx + c)
- printf("Equation of the line: y = %.2fx + %.2f\n", slope, intercept);
- return 0;
- }
复制代码
Replace the existing x and y arrays with your given data. The program will calculate the slope and intercept of the line that best fits the data and print the equation of the line.
随便拿个在线编译器跑一下,结果是 Equation of the line: y = 1.06x + -0.30。和2楼结果一致。 |
|