8.9. Establishing Relationships Between Variables

Problem

You need to establish a relationship between two independent variables. These variables could be temperature versus energy use or the number of news channels versus stress-related ailments; you need to measure the correlation between two variables.

Solution

Add data points to an instance of Commons Math SimpleRegression. This class will calculate the slope, slope confidence, and a measure of relatedness known as R-square. The SimpleRegression class performs a least squares regression with one independent variable; adding data points to this model refines parameters to the equation y = ax + b. The following code uses SimpleRegression to find a relationship between two series of values [0, 1, 2, 3, 4, 5] and [0, 1.2, 2.6, 3.2, 4, 5]:

import orgorg.apache.commons.math.stat.multivariate.SimpleRegression; SimpleRegression sr = new SimpleRegression( ); // Add data points sr.addData( 0, 0 ); sr.addData( 1, 1.2 ); sr.addData( 2, 2.6 ); sr.addData( 3, 3.2 ); sr.addData( 4, 4 ); sr.addData( 5, 5 ); // Print the value of y when line intersects the y axis System.out.println( "Intercept: " + sr.getIntercept( ) ); // Print the number of data points System.out.println( "N: " + sr.getN( ) ); // Print the Slope and the Slop Confidence System.out.println( "Slope: " + sr.getSlope( ) ); System.out.println( "Slope Confidence: " + sr.getSlopeConfidenceInterval( ) ); // Print RSquare a measure of relatedness System.out.println( "RSquare: " + sr.getRSquare( ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.