Regula folsi of False position method implementation using perl language


#False position method implementation using perl language......


#---------------------------The given function----------------

sub FalsePosition
{
($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*$x*$x-4*$x-9)
#return (2*$x-3*sin($x)-5);
}
$x0,$x1,$l1,$l2,$r,$f1,$f2,$f3,$iteration=20,$cnt=1;

#--------------------------Function for finding a & b-----------------------

    for($k=-20;$k<=$iteration;$k++){
        if(&FalsePosition($k)>0){
            if(&FalsePosition($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\n";
                last;
            }
        }
        if(&FalsePosition($k)<0){
            if(FalsePosition($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 "--------------------------Iteration start-------------------------\n\n";
$l1=   $x0;
$l2=   $x1;

#--------------------------Function for finding actuall Root of the given function------------------

if(&FalsePosition($l1)==0){
 $r=$l1;
}

elsif(&FalsePosition($l2)==0){
 $r=$l2;
}

 else {
  while($cnt<=$iteration){
             $f1=&FalsePosition(l1);
            
  #---------------------Equation for Finding root of the function---------------------------------
 
             $r=(($l1*&FalsePosition($l2) -$l2*&FalsePosition($l1))/(&FalsePosition($l2)-&FalsePosition($l1)));
             $f2=&FalsePosition($r);
             $f3=&FalsePosition($l2);

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

             if(($f1*$f2)<0){
                $l2=$r;
            }
            elsif(($f3*$f2)<0){
                $l1=$r;
            }
            $cnt++;
  }
 
  print "\n\n";
  #------------------Approximate root of the function----------------------
 
  print "Approximate root is : ";
  #print ($r);
  print ($root);
  print "\n";

 }

exit;

#MD. Alamgir Hossain
#Dept of Computer Science & Engineering
#Jessore University of Science & Technology, Jessore, Bangladesh

No comments:

Post a Comment