5.1 Developing backend files

In order to bring some functionality with values that are going to be generated by user input, we need functions that take in those inputs and give us something to work with.

Objectives

  • We need to show the estimate and absolute relative error on the Results panel.

  • We need to plot the chosen function and the approximation of the roots on the Graph panel.


I have written a few helper functions for this purpose and they reside in an external file away from the frontend folder. I store all my backend javascript files in a folder called javascript files and then I include the required .js file in the .html file using <script></script> tags. For more information, see - Adding script tags to include js files

To save the hassle of figuring out the logic, and to make this guide easier to follow, here’s the original code:

function getXFirstFunction(x) {
  let new_x = x - ( (Math.pow(x, 2) - 2) / (2*x) );
  let abs_rel_error =  Math.abs( (new_x - x) / new_x ) * 100;
  return ({abs_rel_error: abs_rel_error, new_x: new_x});
}

function getXSecondFunction(x) {
  let new_x = x - ( Math.cos(x) / ( -1 * Math.sin(x ) ) );
  let abs_rel_error =  Math.abs( (new_x - x) / new_x ) * 100;
  return ({abs_rel_error: abs_rel_error, new_x: new_x});
}

function getXThirdFunction(x) {
  let new_x = x - ( (Math.pow(x, 3) - 7) / ( 3 * Math.pow(x, 2) ) );
  let abs_rel_error =  Math.abs( (new_x - x) / new_x ) * 100;
  return ({abs_rel_error: abs_rel_error, new_x: new_x});
}

function getXFourthFunction(x) {
  let new_x = x - ( ( Math.pow(x, 3) - ( 3 * Math.pow(x, 2) ) + x - 1 ) / 
  ( ( 3 * Math.pow(x, 2) ) - (6 * x) + 1) );
  let abs_rel_error =  Math.abs( (new_x - x) / new_x ) * 100;
  return ({abs_rel_error: abs_rel_error, new_x: new_x});
}

function getYFirstFunction(x) {
  return (Math.pow(x, 2) - 2);
}

function getYSecondFunction(x) {
  return Math.cos(x);
}

function getYThirdFunction(x) {
  return (Math.pow(x, 3) - 7);
}

function getYFourthFunction(x) {
  return ( Math.pow(x, 3) - ( 3 * Math.pow(x, 2) ) + x - 1 );
}