Linear Data Fitting

This example demonstrates a simple usage of fit() to fit 3 data points to the line y=mx+b. This is all you need to get started!

dataset=(1,1),(2,1),(3,2)

Try plotting the data points and program output in a graphing calculator! Does it fit?

Follow these steps to create a new project workspace and install the datafit dependency to run this example.

# Create and open project folder
mkdir Linear_Data_Fitting_demo
cd Linear_Data_Fitting_demo
# Initialize project and install dependencies
npm init -y
npm i datafit@1.4.8
# Create and open source file
touch "Linear Data Fitting.mjs"
open "Linear Data Fitting.mjs"

Copy and paste this source code into Linear Data Fitting.mjs.

import { fit } from 'datafit';

// Define our model function: y=mx+b
function f(x, m, b) {
return m * x + b;
}

// Define our dataset
const data = [
{ x: 1, y: -1 },
{ x: 2, y: 1 },
{ x: 3, y: 2 },
];

// Compute the best fit parameters to
// get `m` and `b`, and print result.
const summary = fit(f, data);
const m_fit = summary.params[0];
const b_fit = summary.params[1];
console.log('The best-fit line is y = ' + m_fit.toFixed(2) + 'x + ' + b_fit.toFixed(2));

In Linear_Data_Fitting_demo/, execute Linear Data Fitting.mjs with NodeJS to generate an output.

node "Linear Data Fitting.mjs"

You should expect to see an output similar to the one below.

The best-fit line is y = 1.49x + -2.31
MMNEPVFCICPMFPCPTTAAATR