Advertisement
cdsatrian

bisection

Mar 8th, 2017
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.73 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Bisection
  5.  * The Bisection Function
  6.  * @param array $pol The array that represent the polynomial function, in the form array( 'grade' => 'coefficient' );
  7.  * @param int $a Inferior limit
  8.  * @param int $b Superior limit
  9.  * @param real $precision Root precision
  10.  * @param int $loop
  11.  * @return float The root
  12.  */
  13. function bisection( array $pol, $a, $b, $precision = 0.01, $loop = 100 ){
  14.  
  15.     do{
  16.         $c = ( $a + $b ) / 2;
  17.        
  18.         $yc = calculate( $pol, $c );
  19.        
  20.         if( getSign( $yc ) === getSign( calculate( $pol, $a ) ) ){
  21.             $a = $c;
  22.         }else{
  23.             $b = $c;
  24.         }
  25.        
  26.         $loop--;
  27.        
  28.     }while( ( ( $yc >= $precision ) || ( $yc <= (0 - $precision) ) ) && $loop > 0 );
  29.    
  30.     return $c;
  31. }
  32.  
  33. /**
  34.  * Calculate
  35.  * Calculate the Y of the $pol polynomial function in $x
  36.  * @param array $pol The array that represent the polynomial function, in the form array( 'grade' => 'coefficient' );
  37.  * @param float $x The X
  38.  * @return float The Y
  39.  */
  40. function calculate( array $pol, $x ){
  41.     $res = 0;
  42.     foreach( $pol as $exp => $coeff ){
  43.         $res = $res + ( $coeff * pow( $x, $exp ) );
  44.     }
  45.     return $res;
  46. }
  47.  
  48. /**
  49.  * GetSign
  50.  * Get the sign of the y
  51.  * @param float $y The Y
  52.  * @return string '+' or '-';
  53.  */
  54. function getSign( $y ){
  55.     return ( $y >= 0 ) ? '+' : '-';
  56. }
  57.  
  58. /**
  59.  * isValid
  60.  * Check if the given limits are valid
  61.  * @param array $pol The array that represent the polynomial function, in the form array( 'grade' => 'coefficient' );
  62.  * @param int $a Inferior limit
  63.  * @param int $b Superior limit
  64.  * @return bool false on invalid limits
  65.  */
  66. function isValid( $pol, $a, $b ){
  67.     if( $a >= $b ){
  68.         return false;
  69.     }
  70.    
  71.     if( getSign( calculate( $pol, $a ) ) == getSign( calculate( $pol, $b ) ) ){
  72.         return false;
  73.     }
  74.  
  75.     return true;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement