Bisection method implementation using perl language


#Bisection method implementation using perl language......

sub log10
{
 ($y)=@_;
  return (log($y)/log(10));
}
#--------------------The given function ---------------------------
sub bisection
{
($x)=@_;
#return (($x*$x)-(5*$x)+2);

#return (2*$x-3-cos($x));
return (($x*$x*$x) - (21*$x)+3500);
#return ($x*$x-5*$x+2);
#return ($x*&log10($x))-1.2;
#return ($x)*ln($x)-1.2;
#return ($x*$x*$x)-(4*$x)-9;
#return $x*exp($x)-2;
}

#$resss= &bisection(1);
#print ($resss);
$x0,$x1,$l1,$l2,$r,$f1,$f2,$f3,$iteration=20,$cnt=1;

#--------------------Finding a and b----------------------

    for($k=-20;$k<=$iteration;$k++){
        if(&bisection($k)>0){
            if(&bisection($k+1)<0){
                $x0=$k;
                $x1=$k+1;

                print "a= ";
                print ($x0);

                print " and F(x) is positive. b = ";
                print ($x1);
                print ", and F(x) is Negative \n";
                last;
            }
        }
        if(&bisection($k)<0){
            if(&bisection($k+1)>0){
                $x0=$k;
                $x1=$k+1;
                print "a = ";
                print ($x0);
                print " and F(x) is Negative. b = ";

                print ($x1);
                print " and F(x) is Positive \n\n";
                last;
            }
        }


}

  print "---------------------------Iteraation part------------------------\n\n";

$l1=   $x0;
$l2=   $x1;

#------Finding root after one by one iteration---------------

if(&bisection($l1)==0){
 $r=$l1;
}
elsif(&bisection($l2)==0){
 $r=$l2;
}
 else {
  while($cnt<=$iteration){
             $f1=&bisection($l1);
             $r=($l1+$l2)/2;
             $f2=&bisection($r);
             $f3=&bisection($l2);

             if($f2==0){
              $r=$f2;
              last;
             }
             print "After Iteration ";
             print ($cnt);
             print " the root is : ";
             print ($r);
             print "\n";

             if(($f1*$f2)<0){
                $l2=$r;
            }
            elsif(($f3*$f2)<0){
                $l1=$r;
            }
            $cnt++;
  }
  #-----------------------------Approximate root or Ans root-----------------------------

  print "\nApproximate root is : ";
  print ($r);
  print "\n";

 }

exit;

No comments:

Post a Comment