JavaScript即时计算标准偏差

发布于 2025-01-21 08:41:43 字数 3372 浏览 0 评论 0原文

我有一些html输入字段,其中名称=“ textfield”。 对于这些输入字段,我想即时计算标准偏差,并将其放入HTML输入字段中。

对于计算,我正在使用此JavaScript代码。

    <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>

第二部分只是按下另一个按钮。

但是我没有在HTML字段中获得输出。我认为我犯了一个错误,将Textfield放入数组中。 但是我没有得到它,找不到错误。 我希望有人可以澄清这个问题。

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

万人眼中万个我 2025-01-28 08:41:43

接受的答案无法正确计算差异和标准偏差。它需要将平方的总和除以n(或n-1)。

校正的计算方差代码:

const variance = arr => {
    const m = mean(arr);
    return (sum(arr.map(v => (v - m) ** 2)) / arr.length);
};

我没有评论的声誉,因此将其作为单独的答案发布。

The accepted answer does not calculate variance and standard deviation correctly. It needs to divide the sum of squares by N (or n-1).

Corrected code for calculating variance:

const variance = arr => {
    const m = mean(arr);
    return (sum(arr.map(v => (v - m) ** 2)) / arr.length);
};

I don't have the reputation to comment, so posting as separate answer.

浅黛梨妆こ 2025-01-28 08:41:43

在计算结果之前,将字段值转换为数字值,并过滤出非数字的值(例如它们是空的)。如果您为数学创建单独的功能,它也将使事情变得容易。

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>

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>

西瓜 2025-01-28 08:41:43

USE以下代码。它对我有用。
您的共享代码在语法方面不完整。

<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>
<script>       
    function dostd(){ 
// YOu should select by name as follows. Using name="value"  
        var btns = document.querySelectorAll('[name="textfield"]'); 
      
        var btnsArr = Array.prototype.slice.call(btns); //Array.prototype.slice.call(btns);         
       // THis array init was missed in you code
        let arr = btnsArr.map((b) => {return b.value})

        let mean = arr.reduce((acc, curr)=>{
            return acc + curr
        }, 0) / btnsArr.length;           
       
        arr = arr.map((k)=>{
            return (k - mean) ** 2
        })
       
         let sum1 = arr.reduce((acc, curr)=> acc + curr, 0);
                  
         let variance = sum1 / arr.length;
          
         sum1 = Math.sqrt(sum1 / arr.length);
        document.getElementById("ergebnis1").value = sum1;
    }        
</script>

Us e the following code. It is working for me.
Your shared code is incomplete in terms of syntax.

<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>
<script>       
    function dostd(){ 
// YOu should select by name as follows. Using name="value"  
        var btns = document.querySelectorAll('[name="textfield"]'); 
      
        var btnsArr = Array.prototype.slice.call(btns); //Array.prototype.slice.call(btns);         
       // THis array init was missed in you code
        let arr = btnsArr.map((b) => {return b.value})

        let mean = arr.reduce((acc, curr)=>{
            return acc + curr
        }, 0) / btnsArr.length;           
       
        arr = arr.map((k)=>{
            return (k - mean) ** 2
        })
       
         let sum1 = arr.reduce((acc, curr)=> acc + curr, 0);
                  
         let variance = sum1 / arr.length;
          
         sum1 = Math.sqrt(sum1 / arr.length);
        document.getElementById("ergebnis1").value = sum1;
    }        
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文