• Welcome to Daffodil International University.
 

News:

Daffodil International University Forum contains information about Open Text material, which is only intended for the significant learning purposes of the university students, faculty, other members, and the knowledge seekers of the entire world and is hoped that the offerings will aide in the distribution of reliable information and data relating to the many areas of knowledge.

Main Menu

Processing Rational input-output in PHP

Started by msu_math, November 13, 2012, 09:51:04 AM

Previous topic - Next topic

msu_math

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;
}
Mohammad Salah Uddin

Lecturer in Mathematics
Department of Natural Sciences
FSIT, DIU

msu_math

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