Ethereum: Average Calculation not Working Well, Result is always NaN
1 min read
Establishment of a nose calculation in Ethereum: the usual question
In the development of Ethereum, in particular in working with strings and budgets, errors such as nan
(not a number) may occur due to the incorrect use and incorrect interpretation of the data. In this article, we will explore why problems are encountered with the calculation of the average of your series and providing guidelines on how to solve them.
Problem: calculation error
Suppose your initial setting is similar to this:
`Javascript
Var array = [1, 2, 3, 4, 5];
`
You want to calculate the average of these values. In Ethereum, you can achieve this goal with the array.prototype.reduce ()
or hand repetition methods on a series.
wrong calculation
Here is an example of the wrong calculation:
Javascript
VAR SUM = 0;
Settenarary (Function () {{{{
for (var i = 0; i
Sum += array [i];
Iche
VAR MEDIA = SUM / Array.length;
}, 1000); // every second
Console.log (media);
`
This code will calculate the average by adding all the elements in a passage, with consequent NAN value.
Solution: correct calculation
To correctly calculate the average, it is necessary to use array.prototype.reduc ()
or repeat on a series using a cycle:
`Javascript
VAR SUM = 0;
Settenarary (Function () {{{{
for (var i = 0; i
Sum += array [i];
Iche
}, 1000); // every second
Console.log (sum / array.length);
`
Or you can use Reduction ()
:
:
Javascript
VAR the SUM = Array.Reduce ((acc, current) => Acca + current, 0);
Console.log (sum / array.length);
`
Additional tips
- Make sure your data is in valid format and do not contain errors.
- When using a string to store the price or value, make sure all the elements are numbers (e.g. number) for accurate budgets.
- If you perform large data sets, take into consideration the use of more effective calculation methods or parallel processing techniques.
Conclusion
In this article, we identified the problem of incorrect calculations when the average of the value from a series in Ethereum. By understanding why the initial setting was wrong and by applying the correct logic, it is possible to improve the accuracy of the code and guarantee reliable results.