What could be causing the NaN result?

Currently diving into the realm of Javascript, I have encountered an issue where my calculated data is returning as NaN.

The desired output should 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];

I suspect there might be a flaw in my code causing this unexpected outcome. Can you help me identify it?

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

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

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

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

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

Answer №1

To solve this issue, it's crucial to calculate the values of ar[i], which rely on ma[i-1], and ma[i], which depend on ar[i], in the correct order within a single loop.

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

// Calculate AR and MA simultaneously
ar[0] = temperature[0]
for (var i = 0; i < temperature.length; i++) {

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

  ma.push(Math.abs(temperature[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 precision of the results extends beyond 2 decimal places, ensuring accurate calculations for subsequent values. Adjust the precision as needed once all values have been computed.

Answer №2

What course of action would be most appropriate?

The relationship between calculating the values in ar and ma seems intertwined. To calculate ar[i], you require ma[i-1], and for ma[i], you need ar[i]. This necessitates a unified approach. It is not feasible to compute one array before moving onto the next.

var temperature = [37, 36, 39, 38, 38, 38, 40, 41, 41, 39];
var ar = [temperature[0]];
var ma = [0];

for (let i = 1; i < temperature.length; ++i) {
  ar[i] = 0.99 * temperature[i - 1] + 0.06 * ma[i - 1];
  ma[i] = Math.abs(temperature[i] - ar[i]);
}

console.log(ar);
console.log(ma);
.as-console-wrapper{top:0;max-height:100%!important}

Answer №3

By failing to initialize the ma[] array at the beginning and using it to initialize ar[], you are encountering NaN values.

Answer №4

NaN in JavaScript is an abbreviation for Not a Number, indicating that the value is not a valid number. It can be utilized to validate whether an input is a proper number or not.

Accessed from this source.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Elements with absolute positioning are preventing drag events from executing

Struggling to create a slider and encountering an issue. The problem lies in absolute items blocking slider drag events. I need a solution that allows dragging the underlying image through absolute positioned items. Any ideas on how to achieve this? MANY T ...

"Disabling Dropzone.js functionality once a file has been selected - here's how

When using my dropzone, I typically choose a file to save first and then click the save button. However, I am facing an issue: how can I disable the dropzone area after selecting a file? I attempted the following approach: accept: function (file, done) { ...

Utilizing HTML and Javascript for streaming audio and recording voice

Working on a new project that involves streaming audio files (mp3) and recording voice messages. Initially considered using Flash, but the challenge is making the website iPhone-friendly as per the client's request. Is there a technology available th ...

Experiencing the issue with the $.getJSON function bug

Is there a way to ensure that my code processes the $.getJSON function fully? I am encountering an issue where only the first alert, 'inside1', is triggered when running the site. The second alert, 'inside x2', never gets processed. Any ...

Retrieve class attributes within callback function

I have integrated the plugin from https://github.com/blinkmobile/cordova-plugin-sketch into my Ionic 3 project. One remaining crucial task is to extract the result from the callback functions so that I can continue working with it. Below is a snippet of ...

retrieve information from an array of objects that include promises

Within my react application, I am faced with the task of retrieving email and name data for various user IDs from separate API endpoints. To achieve this, I follow these steps: const promises = ids.map( id => ( {email: axios.get(`blabla/${id}/email ...

The spread operator in Vuex is causing compilation errors with babel, as it continuously results in a module build failure

Currently, I am utilizing a spread operator within my mapGetters object. It is crucial to use a specific babel-preset-stage for proper ES6 compilation. Even after installing babel-preset-stage-2 via npm, I encountered the following error: ERROR in ./~/bab ...

Is there a feature in Angular JS similar to dojo.hitch()?

I apologize for my lack of knowledge in AngularJS. I am wondering if there exists a similar function to dojo.hitch() within AngularJS. dojo.hitch() returns a function that is ensured to be executed in the specified scope. ...

Press a button and use an if statement to compare the text variable

Can you please assist me with this query? I'm attempting to click on three different buttons with unique IDs, based on a JavaScript string variable. For example: function my_custom_js_func(){ jQuery( "#listViewer" ).click(); }; However, this co ...

Decreased storage space requirements following transfer to S3 bucket using nodejs

I am currently facing an issue with uploading files from a specific folder location to an S3 bucket using the nodejs aws-sdk. The files I am working with are deepzoom images (.dzi). While the files seem to be successfully uploaded to my S3 bucket, I have n ...

Customizing the color of text in the fillText() function on an HTML5 <canvas>

I need help changing the color of each line of text in my canvas messages. I've tried creating variables for them, but haven't had any success. Any assistance would be greatly appreciated. function initialize(){ var elem = document.getElemen ...

Using Strapi to showcase images in a React frontend

I am currently in the process of developing a website utilizing Strapi as a Content Management System (CMS) and Next.js with React for the Frontend. The website features an image slider that includes an image, a headline, and a description. While I have su ...

Dynamically insert textboxes into a form by leveraging the power of the Jade template engine

Looking for a solution to a simple requirement that doesn't seem to have a clear answer online. I need a combobox on my jade page that accepts numbers as input. When the user selects a number, I want the page to refresh and display that many textboxes ...

I am looking for a method to provide access to files located outside of the public folder in Laravel

Imagine <link rel="stylesheet" href="{{asset('css/style.css')}}"> is used to retrieve the style.css file from the public folder. How can I access a file that is located in the resources folder in a similar way? ...

PHP can be executed and accessed directly from JavaScript without the need for any form submission

While I have come across a lot of information on PHP post/get methods for transmitting data, I find myself stuck with an interesting issue that requires some assistance. My HTML page contains data in different inputs, and I run algorithms on the JavaScrip ...

Is Redux really the new trend in the world of action creators?

I am new to this. I'm a bit unsure, is it okay or silly to use the pattern below? import { createAction, handleActions } from "redux-actions"; const CHANGE_STATE = "appState/CHANGE_STATE"; export const changeState = createAction(CHANGE_STATE, (key, ...

Steps to halt webkit animation within a div located inside a circle:

I have a series of nested circle divs, and I want to give them a pulse animation. The issue is that the text container is within one of these circles, causing the animation to apply to the text as well. I am unable to move the text container due to potenti ...

Delay the axios get request in the useEffect

Working with React JS, I have implemented a useEffect hook to request data from a database via an Express server when the page renders. However, if the server is down, the app will continue to make thousands of requests until it crashes. Is there a way to ...

Modifying the array structure will deselect all individual <Input> elements that have been iterated

Hoping to create a system for adding/removing sub-items with buttons that increment/decrement slots in an array, where input fields are automatically added and removed: <div *ngFor="let item of itemsInNewOrder; let i = index"> <input [(ngModel) ...