javascripthtmlstandard-deviation

javascript calculating standard deviation on the fly


I have some Html Input fields with the name="textfield". For those input fields i want to calculate the standard deviation on the fly and put it into a html input field.

for the calculation i am using this javascript code.

    <script type="text/javascript">
        function doSum() {
            var fields = document.getElementsByName("textfield");
            var sum = 0;
            for (var i=0; i<fields.length; i++) {
                var v = parseInt(fields[i].value, 10);
                if (isNaN(v)) v = 0;
                sum += v;
            }
            
            document.getElementById("ergebnis").value = sum;
            
        }
        </script>       
        
        <script>
        // Javascript program to calculate the standered deviation of an array
        function dostd(){
            // Get all buttons as a NodeList    
            var btns = document.querySelectorAll('[textfield]'); 
            // Convert buttons NodeList to an array
            var btnsArr = Array.prototype.slice.call(btns); 
            let arr = btnsArr.map((b) => {return b.value})          
            // Creating the mean with Array.reduce
            let mean = arr.reduce((acc, curr)=>{
            return acc + curr
            }, 0) / btnsArr.length;
           
          // Assigning (value - mean) ^ 2 to every array item
          arr = arr.map((k)=>{
            return (k - mean) ** 2
          })
           
          // Calculating the sum of updated array
         let sum1 = arr.reduce((acc, curr)=> acc + curr, 0);
          
         // Calculating the variance
         let variance = sum1 / arr.length;
          
         // Returning the Standered deviation
         sum1 = Math.sqrt(sum1 / arr.length);
        document.getElementById("ergebnis1").value = sum1;
        }
        
        </script>
        

<form name="form1" method="post" action="">         
        <table>
            <tr>
                <th>Messwert 1</th>
                <th><input type="text" name="textfield" id="breite_mess1" onChange="doSum();dostd();"></th>
            </tr>
            <tr>
                <th>Messwert 2</th>
                <th><input type="text" name="textfield" id="breite_mess2" onChange="doSum();dostd();"></th>
            </tr>
        </table>        
</form>     

        <?php           
        if(isset($_POST['submitcct']))
        {

        require("artikel_info_ziehen.php");     
        
        if ($result1->num_rows > 0) {
            $row = $result1->fetch_assoc();

        echo"<form name='Formular'>";           
        echo"<table>";
        echo"<p>Nennmaß (mm): " . $row["Breitemm"]. " </p>";
        echo"<p>Toleranz(±) (mm): " . $row["ToleranzBreitmm"]. "</p>";
        echo"<p>Mittelwert (mm):<input type='text' id='ergebnis' disabled></p>  ";
        echo"<p>Standardabweichung (mm):<input  type='text' id='ergebnis1' disabled></input>";
        echo"</table>";     
        echo"</form>";  
        
                } else {
            echo "0 results";
        }   
        
        }
        ?>  
        </script>

the second part just appears as a other button is pressed.

but i dont get the output in the html field. i think i made a mistake at putting the textfield into an array. But i dont get it and cant find the mistake. I hope someone can clarify the problem.

thx


Solution

  • Convert the field values to numeric values and filter out those that are non-numeric (e.g. because they are empty) before calculating the results. It will also make things easier if you create separate functions for the maths.

    const sum = arr => arr.reduce((partialSum, a) => partialSum + a, 0);
    const mean = arr => sum(arr) / arr.length;
    const variance = arr => {
      const m = mean(arr);
      return sum(arr.map(v => (v - m) ** 2));
    };
    const sd = arr => Math.sqrt(variance(arr));
    
    function dostd() {
      const values = [...document.querySelectorAll('[name="textfield"]')]
        .map(b => parseFloat(b.value))
        .filter(v => !isNaN(v));
      document.getElementById("ergebnis1").value = sd(values);
    }
    <input name="textfield" />
    <input name="textfield" />
    <input name="textfield" />
    <input name="textfield" />
    <input name="textfield" />
    <input name="textfield" />
    <textarea id="ergebnis1" ></textarea>   
    <button onclick="dostd()">Check</button>