计算一系列值的斜率

编程入门 行业动态 更新时间:2024-10-10 05:19:42
本文介绍了计算一系列值的斜率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有2个相等长度的数组.以下函数尝试使用这些数组来计算斜率.它返回每个点之间的斜率的平均值.对于以下数据集,我似乎得到的值不同于Excel和Google文档.

I have 2 arrays of equal length. The following function attempts to calculate the slope using these arrays. It returns the average of the slope between each points. For the following data set, I seem to be getting different values than Excel and Google Docs.

double[] x_values = { 1932, 1936, 1948, 1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980 }; double[] y_values = { 197, 203, 198, 204, 212, 216, 218, 224, 223, 225, 236 }; public static double getSlope(double[] x_values, double[] y_values) throws Exception { if (x_values.length != y_values.length) throw new Exception(); double slope = 0; for (int i = 0; i < (x_values.length - 1); i++) { double y_2 = y_values[i + 1]; double y_1 = y_values[i]; double delta_y = y_2 - y_1; double x_2 = x_values[i + 1]; double x_1 = x_values[i]; double delta_x = x_2 - x_1; slope += delta_y / delta_x; } System.out.println(x_values.length); return slope / (x_values.length); }

输出

Google:0.755

Google: 0.755

getSlope():0.962121212121212

getSlope(): 0.962121212121212

Excel:0.7501

Excel: 0.7501

推荐答案

我敢打赌其他两种方法都在计算最小二乘拟合,而您不适合.

I bet the other two methods are computing the least-squares fit, whereas you are not.

当我使用 R 验证这个猜想时,我也得到了约0.755的斜率:

When I verify this conjecture using R, I too get the slope of about 0.755:

> summary(lm(y~x)) Call: lm(formula = y ~ x) Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -1.265e+03 1.793e+02 -7.053 5.97e-05 *** x 7.551e-01 9.155e-02 8.247 1.73e-05 ***

相关数字为7.551e-01.还值得注意的是,这条生产线的截距约为-1265.

The relevant number is the 7.551e-01. It is also worth noting that the line has an intercept of about -1265.

这是最小二乘拟合的图片:

Here is a picture of the least-squares fit:

有关在代码中实现此操作的信息,请参见使用Java计算最小二乘法

As to implementing this in your code, see Compute least squares using java

更多推荐

计算一系列值的斜率

本文发布于:2023-11-30 06:53:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649086.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:斜率   系列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!