# Apache Simple Linear Regression In Java using Math Library

go评论44阅读模式

Apache Simple Linear Regression In Java using Math Library

# 问题

I am quite a newbie in using the apache library for a simple linear regress.
Task: I want to calculate the slope.

I have two linear lists, i.e., x-list and y-list. Y list values are the series of number. I am populating x-list by fetching value from a hashmap.

However, when I am trying to apply simpleRegression utility of apache library I am facing below difficulty:

Here is my code:

``````while(i < segmentI) {
i++;
}
for(int m=0; i < segmentI; i++) {
{xList.get(m),yList.get(m)}
});
}
``````

Doubt: Is there any way can I create new double[][] before passing it to simpleRegression.

Also, new double[][]-it is a matrix then what would be the value of [0,1], [0,2]... so on because we don't have anything like that in single ArrayList.

Anything in this regard will be helpful.

I am quite a newbie in using the apache library for a simple linear regress.
Task: I want to calculate the slope.

I have two linear lists, i.e., x-list and y-list. Y list values are the series of number. I am populating x-list by fetching value from a hashmap.

However, when I am trying to apply simpleRegression utility of apache library I am facing below difficulty:

Here is my code:

``````while(i&lt; segmentI)
{
i++;
}
for(int m=0; i&lt; segmentI; i++)
{
{xList.get(m),yList.get(m)}
});

}
``````

Doubt: Is there any way can I create new double[][] before passing it to simpleRegression.
Also, new double[][]-it is a matrix then what would be the value of [0,1], [0,2]... so on because we don't have anything like that in single ArrayList.

Anything in this regard will be helpful.

# 答案1

``````double[][] data = new double[1][2];

for(int m=0; m < segmentI; m++)
{
data[0][0] = xList.get(m);
data[0][1] = yList.get(m);
}
``````

``````simpleRegression.addData(xList.get(m), yList.get(m));
``````

> Is there any way can I create new double[][] before passing it to simpleRegression

Yes. For example

``````            double[][] data = new data[1][2];

for(int m=0; m &lt; segmentI; m++)
{
data[0][0] = xList.get(m);
data[0][1] = yList.get(m);
}
``````

You know there's also a method that you can call without an array?

``````simpleRegression.addData(xList.get(m), yList.get(m));
``````

# 答案2

double[][] pqr={ArrayUtils.toPrimitive(yList.toArray(new Double[0])),ArrayUtils.toPrimitive(xList.toArray(new Double[0]))};

This worked with below changes:
double[][] pqr={ArrayUtils.toPrimitive(yList.toArray(new Double[0])),ArrayUtils.toPrimitive(xList.toArray(new Double[0]))};

• 本文由 发表于 2020年8月2日 07:46:29
• 转载请务必保留本文链接：https://go.coder-hub.com/63211079.html
• java
• linear-regression

go 38

go 41

go 37

go 35