JavaScript. Cubic regression

A cubic regression uses this expression:
regresion24
You can study polynomial regression in:

To get parameters A, B, C and D by JavaScript, we can use this code with the library numeric.min.js (https://cdnjs.cloudflare.com/ajax/libs/numeric/1.2.6/numeric.min.js)

JavaScript code adapted my application in App Inventor (regresion_cubica.htm):

<!DOCTYPE html>
<html><head><meta charset=utf-8 />
 <script src="numeric.min.js"></script>
</head><body>
 <script> 
 
var datos =  window.AppInventor.getWebViewString() ; // Obtiene los datos.
       datos = datos  + ":" ;

var partes = datos.split(":"); 
var data_x = eval('[' + partes[0] + ']');
var data_y = eval('[' + partes[1] + ']');

 // var data_x = [1,2,3,4,5,6,7,8,9];
 // var data_y = [135,245,354,481,655,836,1109,1702,2054];

var cubic = function(params,x) {
  return params[0] * x*x*x +
    params[1] * x*x +
    params[2] * x +
    params[3];
};

var objective = function(params) {
  var total = 0.0;
  for(var i=0; i < data_x.length; ++i) {
    var resultThisDatum = cubic(params, data_x[i]);
    var delta = resultThisDatum - data_y[i];
    total += (delta*delta);
  }
  return total;
};

var initial = [1,1,1,1];
var minimiser = numeric.uncmin(objective,initial);

var todo = "";
for(var j=0; j<minimiser.solution.length; ++j) {
  todo = todo + minimiser.solution[j].toFixed(4) + ",";
}
window.AppInventor.setWebViewString("" + todo);  // Respuesta a CadenaDeWebView
 </script> 
</body></html>


p166B_javascript_regresion.aia (32.8 KB)

Regards,
Juan A. Villalpando.
http://kio4.com/appinventor/166B_javascript_regresion.htm

3 Likes

@Juan_Antonio this is great work, thank you for sharing :pray:

2 Likes

@Juan_Antonio when complied your .aia to .APK it doesn’t seem to work. Maybe simple mistake on my end but would you know why it wouldn’t be working for me? Tried granting permission for app storage but still nothing. Wondering if maybe it is not reading directory properly? Please let me know. Thank you and God bless.

UPDATE: it works on my ai companion but still doesn’t work when compiled to apk. This makes me believe that it could have something to do with file directory. Please let me know. Thank you again.

Before compiling (Build) you must change:

file:///mnt/sdcard/AppInventor/assets/regresion_cubica.htm

for

file:///android_asset/regresion_cubica.htm

@Juan_Antonio thank you for your quick message back. Good news - that small change worked. The app is now working with pura vida loco! :joy: :nerd_face: :innocent: :pray:

CC: @Taifun

(added to JavaScript stunts FAQ)