Author Topic: Processing Rational input-output in PHP  (Read 709 times)

Offline msu_math

  • Jr. Member
  • **
  • Posts: 81
    • View Profile
Processing Rational input-output in PHP
« on: November 13, 2012, 09:51:04 AM »
Like integers and floats, variable to process fractions(rational numbers) can’t be declared directly in the programming languages. But in many programming cases, rational input-output becomes a matter of interest. Here we show that rational input-output can be processed by using string variable in an easier way.

A number x is said to be a rational number if there exists integer p and nonzero integer q such that x = p/q. Then p is called the numerator of x and q is called the denominator of x. Since any integer m equals m/1, integers can be considered as rational numbers with denominator 1. A string of digits consisting of only a single “/” at an interior position can be considered as a rational number with numerator, the integer formed by the digits preceding the slash and denominator, the integer formed by the digits following the slash.

Before we start any basic operation with strings representing rational inputs, it is prerequisites that we check whether a string represents a valid rational number or not. By a valid rational number we mean a string of digits containing exactly one “/” at an interior position.

The following function (PHP code) test whether the string $A represents a valid rational number or not.


function FracCheck($A)

{
   $i=0;
   $len=strlen($A)-1;
   $CheckSlash=0;

   if($A[0]=="/" || $A[$len]=="/" || ($A[0]=="-" && $A[1]==NULL)) 
        return 0;

   while($i<=$len)
     {
        if(is_numeric($A[$i]) || $A[$i]=="/" || $A[$i]=="-")
           {
               if($i>0 && $A[$i]=="-" && !($A[$i-1]=="/"))
                     return 0;
               if($A[$i]=="/")
                    $CheckSlash++;
           }
         
        else
                return 0;     
        $i++;
     }

     if($CheckSlash<=1)
           return 1;
     else
          return 0;
}
« Last Edit: November 15, 2012, 09:57:33 AM by msu_math »
Mohammad Salah Uddin

Lecturer in Mathematics
Department of Natural Sciences
FSIT, DIU

Offline msu_math

  • Jr. Member
  • **
  • Posts: 81
    • View Profile
Re: Processing Rational input-output in PHP
« Reply #1 on: November 18, 2012, 11:54:41 AM »
Sample return values:

FracCheck("-5/7");    Return value:  1

FracCheck("-3/5/7");    Return value:  0   
         
      *Because "-3/5/7" is not a valid fraction. ("-3/5/7" contains more than one "/")

FracCheck("51/7p");    Return value:  0   

      *Because "51/7p" is not a valid fraction. ("51/7p" contains non-digit character "p")
Mohammad Salah Uddin

Lecturer in Mathematics
Department of Natural Sciences
FSIT, DIU