ഈ പരിഹാരത്തിൽ, പിഎച്ച്പിയിൽ സ്ട്രിംഗ് എങ്ങനെ ഫ്ലോട്ടിലേക്ക് പരിവർത്തനം ചെയ്യാമെന്ന് ഞങ്ങൾ പഠിക്കും.
പരിഹാരം 1.
നൽകിയ (പോസിറ്റീവ്) ഫ്ലോട്ടിംഗ് പോയിന്റ് നമ്പറിന്റെ യുക്തിസഹമായ ഏകദേശ കണക്ക് കണ്ടെത്തുന്ന PHP ഫംഗ്ഷൻ, $tolerance-ൽ താഴെയുള്ള ആപേക്ഷിക പിശക്.
<?php
function float2rat($n, $tolerance = 1.e-6) {
$h1=1; $h2=0;
$k1=0; $k2=1;
$b = 1/$n;
do {
$b = 1/$b;
$a = floor($b);
$aux = $h1; $h1 = $a*$h1+$h2; $h2 = $aux;
$aux = $k1; $k1 = $a*$k1+$k2; $k2 = $aux;
$b = $b-$a;
} while (abs($n-$h1/$k1) > $n*$tolerance);
return "$h1/$k1";
}
printf("%s\n", float2rat(66.66667)); # 200/3
printf("%s\n", float2rat(sqrt(2))); # 1393/985
printf("%s\n", float2rat(0.43212)); # 748/1731