Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the output NaN?

I’m learning Javascript, when I want to calculate using a formula the resulting data is NaN.

I want the resulting data to be

ar = [37, 36.63, 35.68, 38.81, 37.67, 37.64, 37.64, 39.74, 40.67, 40.61];

ma = [0.00, 0.63, 3.32, 0.81, 0.33, 0.36, 2.36, 1.26, 0.33, 1.61];

Is there something wrong with my code that is making me get this answer?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var suhu = [37, 36, 39, 38, 38, 38, 40, 41, 41, 39];

var ar = []
var ma = []
var temp = 0

// AR
for (var i = 1; i < suhu.length; i++) {
  ar[0] = suhu[0]
  temp = 0.99 * suhu[i - 1] + 0.06 * ma[i - 1]
  ar.push(temp)
}

// MA
for (var j = 0; j < suhu.length; j++) {
  suhu[j] = Math.abs(suhu[j] - ar[j]);
  ma.push(suhu[j])
}

console.log(ar);
// 37, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN
console.log(ma);
// 0, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN

>Solution :

The problem is that the calculation of ar[i] depends on ma[i-1] and ma[i] depends on ar[i] so you need to calculate these in the right order in a single loop.

const suhu = [37, 36, 39, 38, 38, 38, 40, 41, 41, 39];
const ar = [];
const ma = [];

// Calucate AR and MA together
ar[0] = suhu[0]
for (var i = 0; i < suhu.length; i++) {

  if (i > 0)
    ar.push(0.99 * suhu[i - 1] + 0.06 * ma[i - 1])

  ma.push(Math.abs(suhu[i] - ar[i]));
}

console.log(ar);
// [37, 36.63, 35.6778, 38.809332, 37.66855992, 37.639886404799995,
//  37.641606815711995, 39.74150359105728, 40.66550978453656, 40.6100694129278]
console.log(ma);
// [0, 0.6300000000000026, 3.3222000000000023, 0.8093319999999977, 0.33144008000000014,
//  0.36011359520000497, 2.358393184288005, 1.2584964089427189, 0.3344902154634397, 1.6100694129277997]
.as-console-wrapper{top:0;max-height:100%!important}

The results are accurate to more than 2 decimal places and you will need that to calculate the next values correctly. You can change the precision once all the values have been calculated though.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading