Doing Math with Fractions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
braveryonions
Forum Newbie
Posts: 14
Joined: Wed Feb 11, 2009 3:31 pm

Doing Math with Fractions

Post by braveryonions »

pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


I've created some code that provides information about a given quadratic equation (because I HATE repetitive, time-consuming things). However, it only accepts input in decimal form, and only gives output in decimal form. I need it to be able to accept fraction inputs and to give a fraction if the output is not a whole number. I cannot provide a working link, as I am simply running it on my home computer for personal use, but here is the code:

Code: Select all

<?
 
// Has the user provided input?
 
if (!isset($_GET['submit'])) {
 
// No
 
// Input page
 
?><html>
<head>
<title>Quadratic Equation Table Maker XTREME!</title>
</head>
<body>
<center>
<h1>Quadratic Equation<br>Table Maker XTREME!</h1>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="get"><i>y</i>=<input type="text" size="2" value="a" name="a"><i>x</i><sup>2</sup>+<input type="text" size="2" value="b" name="b"><i>x</i>+<input type="text" size="2" value="c" name="c"><br><br><input type="submit" value="Make Table" name="submit"></form>
</center>
</body>
</html><?
 
}
 
else {
 
// Yes
 
// Get variables
 
$a = $_GET['a'];
$b = $_GET['b'];
$c = $_GET['c'];
 
// Idiot check
 
if(!is_numeric($a) || $a == '0') { echo '<center><h1>The input "'.$a.'" for <i>a</i> is not valid.</h1></center>';  }
if(!is_numeric($b)) { echo '<center><h1>The input "'.$b.'" for <i>b</i> is not valid.</h1></center>';  }
if(!is_numeric($c)) { echo '<center><h1>The input "'.$c.'" for <i>c</i> is not valid.</h1></center>';  }
if(!is_numeric($a) || !is_numeric($b) || !is_numeric($c) || $a == 0) { echo '<center><h1>You suck at numbers.<br>Try again:</h1><form action="'.$_SERVER['PHP_SELF'].'" method="get"><i>y</i>=<input type="text" size="2" value="a" name="a"><i>x</i><sup>2</sup>+<input type="text" size="2" value="b" name="b"><i>x</i>+<input type="text" size="2" value="c" name="c"><br><br><input type="submit" value="Make Table" name="submit"></form>'; die(); }
 
// Calculate x values
 
$vertex = (-($b)) / (2 * ($a));
$minus3 = $vertex - 3;
$minus2 = $vertex - 2;
$minus1 = $vertex - 1;
$plus1 = $vertex + 1;
$plus2 = $vertex + 2;
$plus3 = $vertex + 3;
 
// Display output page
 
?><html>
<head>
<title>Quadratic Equation Table Maker XTREME!</title>
</head>
<body>
<center>
<h1>Quadratic Equation<br>Table Maker XTREME!</h1>
<? echo '<i>y</i>='.$a.'<i>x</i><sup>2</sup>+'.$b.'<i>x</i>+'.$c; ?><br>
<br>Graph opens <? if($a > 0) { echo 'UP'; } else { echo 'DOWN'; } ?>.<br>Vertex: (<? echo $vertex; ?>, <? echo (($a) * $vertex * $vertex) + (($b) * $vertex) + ($c); ?>)<br>Axis of symmetry: <i>x</i>=<? echo $vertex; ?><br><br>
<table border="1" cellpadding="3">
<tr>
<th><i>x</i></th>
<th><i>y</i></th>
<th>Substitution</th>
</tr>
<tr>
<tr>
<td><? echo $minus3; ?></td>
<td><? echo (($a) * $minus3 * $minus3) + (($b) * $minus3) + ($c); ?></td></td>
<td><? echo $a.'('.$minus3.')<sup>2</sup>+'.$b.'('.$minus3.')+'.$c; ?></td>
</tr>
<tr>
<td><? echo $minus2; ?></td>
<td><? echo (($a) * $minus2 * $minus2) + (($b) * $minus2) + ($c); ?></td></td>
<td><? echo $a.'('.$minus2.')<sup>2</sup>+'.$b.'('.$minus2.')+'.$c; ?></td>
</tr>
<tr>
<td><? echo $minus1; ?></td>
<td><? echo (($a) * $minus1 * $minus1) + (($b) * $minus1) + ($c); ?></td></td>
<td><? echo $a.'('.$minus1.')<sup>2</sup>+'.$b.'('.$minus1.')+'.$c; ?></td>
</tr>
<tr>
<td><? echo $vertex; ?></td>
<td><? echo (($a) * $vertex * $vertex) + (($b) * $vertex) + ($c); ?></td></td>
<td><? echo $a.'('.$vertex.')<sup>2</sup>+'.$b.'('.$vertex.')+'.$c; ?></td>
</tr>
<tr>
<td><? echo $plus1; ?></td>
<td><? echo (($a) * $plus1 * $plus1) + (($b) * $plus1) + ($c); ?></td></td>
<td><? echo $a.'('.$plus1.')<sup>2</sup>+'.$b.'('.$plus1.')+'.$c; ?></td>
</tr>
<tr>
<td><? echo $plus2; ?></td>
<td><? echo (($a) * $plus2 * $plus2) + (($b) * $plus2) + ($c); ?></td></td>
<td><? echo $a.'('.$plus2.')<sup>2</sup>+'.$b.'('.$plus2.')+'.$c; ?></td>
</tr>
<tr>
<td><? echo $plus3; ?></td>
<td><? echo (($a) * $plus3 * $plus3) + (($b) * $plus3) + ($c); ?></td></td>
<td><? echo $a.'('.$plus3.')<sup>2</sup>+'.$b.'</i>('.$plus3.')+'.$c.'</i>'; ?></td>
</tr>
</table><br>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="get"><i>y</i>=<input type="text" size="2" value="a" name="a"><i>x</i><sup>2</sup>+<input type="text" size="2" value="b" name="b"><i>x</i>+<input type="text" size="2" value="c" name="c"><br><br><input type="submit" value="Make Table" name="submit"></form>
</center>
</body>
</html><?
 
}

pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.
sparrrow
Forum Commoner
Posts: 81
Joined: Mon Oct 20, 2008 12:22 pm

Re: Doing Math with Fractions

Post by sparrrow »

Well, Converting from fraction to decimal is the easiest part. Just display two inputs for num and denom and divide num/denom and use that value in your math. Converting from decimal back to fraction is much more tricky, and I'd have no idea how to easily tell you how. However, a quick Google search for "php convert decimal to fraction" yields that following page though: http://www.weberdev.com/get_example-3824.html
braveryonions
Forum Newbie
Posts: 14
Joined: Wed Feb 11, 2009 3:31 pm

Re: Doing Math with Fractions

Post by braveryonions »

I've tried that script, but I cannot figure out how to make it work. I've been trying to make my own, but have been hung up in two places.

First, I'm trying to define what should be in the denominator (ex. 1; 10; 100; 1,000; etc.) by how many decimal places it goes out to. I can't figure out how to do this. I've exploded at the decimal point, then subtracted the first party of the array from the input, thus leaving the decimal (ex. for an input of 4.21, this gives 0.21), but I don't know where to go from here.

Second, after I've done that, I need to simplify it. I don't know how to find out the GCM.

Edit: All solved! Hoorah!

However, I do have another problem. So not all solved. Before, I validated the input with the is_numeric() function, but I cannot do this is the input is a fraction. What can I do here?
Last edited by braveryonions on Wed Feb 11, 2009 7:22 pm, edited 1 time in total.
sparrrow
Forum Commoner
Posts: 81
Joined: Mon Oct 20, 2008 12:22 pm

Re: Doing Math with Fractions

Post by sparrrow »

For the referenced code, you need both functions. Then you just call it like he has in the first section. That will give you four variables with all the pieces you should need. From there, just display them how you please.

Code: Select all

 list ($whole, $numerator, $denominator, $top_heavy) = convert($decimal); 
 
I also found another solution here http://www.sitepoint.com/forums/showthread.php?t=574331

If you want to reinvent the wheel, then I can think of a few ways to find the smallest denominator. You already found a way to extract down to just the decimal which is good. A big benefit of PHP is the automatic inline type casting. You can manipulate a variable as a string or a number on the fly. This gives you tons of nice functions at your disposal.

...An hour later.... I was going to just give you advice on how to solve the problem yourself, but I am so addicted to writing code and solving puzzles that I wrote an entire function that I believe accomplishes what you are looking for. It's a few more lines of code than the 2nd link I gave, but should run alot quicker. Please let me know if this works.

Code: Select all

function decToFrac($decimal) {
//This function written by Sparrrow, devnetwork.net forums
  $numerator = substr(strrchr($decimal, "."), 1);
  $denominator = str_pad("1", strlen($numerator)+1, "0");
  for ($i=2,$sweetspot="None";$i<=$numerator;$i++) {
    if (!stristr(($numerator/$i), ".") AND !stristr(($denominator/$i), ".")) {
      $sweetspot = $i;
      break;
    } else {
      $sweetspot = "None";
    }
  }
  if (is_int($sweetspot)) {
    $numerator_new = $numerator/$sweetspot;
    $denominator_new = $denominator/$sweetspot;
  } else {
    $numerator_new = $numerator;
    $denominator_new = $denominator;
  }
//echo "Debugging:<br>Decimal: $decimal<br>Improper fraction: $numerator / $denominator <br>Common divisor is $sweetspot<br>Final Fraction: $numerator_new / $denominator_new<br>";
return array('n'=>$numerator_new, 'd'=>$denominator_new);
}


And to use it:

Code: Select all

$mydecimal = 255454.645;
$myfraction = decToFrac($mydecimal);
echo $myfraction['n']." / ".$myfraction['d'];
braveryonions
Forum Newbie
Posts: 14
Joined: Wed Feb 11, 2009 3:31 pm

Re: Doing Math with Fractions

Post by braveryonions »

Thanks, but it seems that we were typing at the same time! Also, is there a way for me to allow inputs of integers, floating point number, AND fractions? I don't know how to do this while still only allowing valid inputs. Right now, I am using is_numeric().
sparrrow
Forum Commoner
Posts: 81
Joined: Mon Oct 20, 2008 12:22 pm

Re: Doing Math with Fractions

Post by sparrrow »

I would allow the user to enter either decimal or fraction in two different prompts, then attempt to use the decimal value first. If the decimal is blank, then try to use the fraction. I would display two different boxes for the two parts of the fraction, and use is_numeric to validate them individually.

Code: Select all

Number: <input name="dec"><br>
Fraction: <input name="frac1"> / <input name="frac2">
You could also try to cast them to ints or floats first to give the user the benefit of the doubt on their input and allow PHP to attempt to use it. This will remove spaces and other invalid characters that may have accidently been entered.

Code: Select all

$dec = (float)$_POST['dec'];
$frac1 = (int)$_POST['frac1'];
$frac2 = (int)$_POST['frac2'];
 
if ($dec) {
  //Calculate with decimal input
} else if ($frac1 && $frac2) {
  //Calculate with fraction input
} else {
  //invalid input
}
If you want to provide a single input box, I guess you could check if it contains a fraction separator by using strpos(), then process the input as either a fraction (explode?) or decimal from there.
Post Reply