<?php
class Fraction
{
const FRACTION_RATIO_ADJUST = true;
const FRACTION_RATIO_KEEP = false;
const FRACTION_FORMAT_DELIMITER = '/';
private $value = [];
public function __construct($x, $y, $adjustRatio=self::FRACTION_RATIO_KEEP)
{
if(!is_int($x) || !is_int($y) || !$y)
{
throw InvalidArgumentException('Invalid fraction parts');
}
$sign = ($x>0&&$y>0) || ($x<0&&$y<0)?1:-1;
$this->value = ['numerator'=>$sign*$x, 'denominator'=>abs($y)];
if($adjustRatio==self::FRACTION_RATIO_ADJUST)
{
$this->adjustRatio();
}
}
public function getNumerator()
{
return $this->value['numerator'];
}
public function getDenominator()
{
return $this->value['denominator'];
}
public function adjustRatio()
{
$gcd = (int)gmp_strval(gmp_gcd(
(string)$this->getNumerator(),
(string)$this->getDenominator()));
$this->setFraction([
'numerator' => $this->getNumerator()/$gcd,
'denominator' => $this->getDenominator()/$gcd
]);
}
public function add(self $fraction, $adjustRatio=self::FRACTION_RATIO_KEEP)
{
$numerator = $this->getNumerator()*$fraction->getDenominator() +
$this->getDenominator()*$fraction->getNumerator();
$denominator = $this->getDenominator()*$fraction->getDenominator();
$this->setFraction([
'numerator' => $numerator,
'denominator' => $denominator
]);
if($adjustRatio==self::FRACTION_RATIO_ADJUST)
{
$this->adjustRatio();
}
}
public function format()
{
$denominator = $this->getDenominator();
$numerator = $this->getNumerator();
return $denominator==1?
(string)$numerator:
(string)($numerator.self::FRACTION_FORMAT_DELIMITER.$denominator);
}
public function __toString()
{
return $this->format();//may be other
}
private function setFraction(array $data)
{
if(!array_key_exists('numerator', $data) || !array_key_exists('denominator', $data))
{
throw InvalidArgumentException('Invalid data structure used in direct set');
}
if(!is_int($data['numerator']) || !is_int($data['denominator']) || !$data['denominator'])
{
throw InvalidArgumentException('Invalid fraction data used in direct set');
}
$this->value['numerator'] = $data['numerator'];
$this->value['denominator'] = $data['denominator'];
}
}
$fraction = new Fraction(8, -12, Fraction::FRACTION_RATIO_KEEP);
echo($fraction->format());//-8/12
$fraction->add(new Fraction(1, 3), Fraction::FRACTION_RATIO_ADJUST);
echo($fraction->format());//-1/3
- Output for git.master, git.master_jit, rfc.property-hooks
- -8/12-1/3
This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.
Active branches
Archived branches
Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page
preferences:
52.51 ms | 401 KiB | 8 Q