在游戏的开发过程中,我们会用到很多的算法,其中数学中的线性回归可以很好地运用到一些游戏里,下面是由PHP写的一段计算线性回归的方程式的代码:
<html> <head> <meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" > <meta name= "GENERATOR" content= "Microsoft FrontPage Express 2.0" > <title>线性回归 Linear Regression</title> </head> <body> <h2>计算线性回归方程式 Y = a + bX</h2> <p> 如果两组数据相关系数很高, 可以用一条近似直线Y=a + bX 来预估, 谓之线性回归<br /> 根据统计学理论, Y = a + bX 中 <br /> 斜率 b = X,Y 离均差交乘积和 / X离均差平方和 <br /> 常数项 a = Y平均值 - b * X平均值<br /> </p> <?php header( "Content-Type: text/html; charset=utf-8" ); if ( empty ( $_REQUEST [ "X" ])) { ?> <form method= "post" action= "index.php" > X : <input type= "text" name= "X" size= "30" value= "25,23,27,35,30" ><br> Y : <input type= "text" name= "Y" size= "30" value= "35,27,36,45,42" ><br> <input type= "submit" value= "ok" > </form> <?php } else { $X = explode ( "," , $_REQUEST [ "X" ]); $Y = explode ( "," , $_REQUEST [ "Y" ]); $xavg = array_sum ( $X )/ count ( $X ); // X 平均值 $yavg = array_sum ( $Y )/ count ( $Y ); // Y 平均值 $XMD = Array(); // X 离均差 $YMD = Array(); // Y 离均差 $mdcross_sum = 0; // X,Y 离均差交乘积和 $xdif_square_sum = 0; // X 离均差平方和 $count = count ( $X ); for ( $i =0; $i < $count ; $i ++) { $xdif = (float) $X [ $i ]- $xavg ; // X 离均差 $ydif = (float) $Y [ $i ]- $yavg ; // Y 离均差 $XMD [ $i ] = $xdif ; $YMD [ $i ] = $ydif ; $mdcross_sum += $xdif * $ydif ; // X,Y 离均差交乘积和 $xdif_square_sum += pow( $xdif , 2); // X 离均差平方和 } //end of for $b = round ( $mdcross_sum / $xdif_square_sum , 2); // 计算斜率 b $a = round ( $yavg - $b * $xavg , 2); // 计算常数项 a echo "X = " .join( ", " , $X ). "<br>" ; echo "Y = " .join( ", " , $Y ). "<br>" ; echo "常数项 a = " . $a . "<br>" ; echo "斜率 b = " . $b . "<br>" ; echo "线性回归方程式 Y = " . $a . " + (" . $b . ")X<br>" ; echo "X 平均值 = " . $xavg . "<br>" ; echo "Y 平均值 = " . $yavg . "<br>" ; echo "X 离均差 = " .join( ", " , $XMD ). "<br>" ; echo "Y 离均差 = " .join( ", " , $YMD ). "<br>" ; echo "X,Y 离均差交乘积和 = " . $mdcross_sum . "<br>" ; echo "X 离均差平方和 = " . $xdif_square_sum . "<br>" ; } echo '<hr />' ; echo '计算两点之间的角度。' ; $a = array ( 'x' => 10, 'y' => 0); $c = array ( 'x' => 80, 'y' => 80); $pi_v = atan2 ( $c [ 'y' ] - $a [ 'y' ], $c [ 'x' ] - $a [ 'x' ]); $n_v = rad2deg( $pi_v ); echo '弧度:' , $pi_v , ' 角度:' , $n_v ; ?> </body> </html> |