PHP 中没有分数类型,只有浮点数,而我们实际开发中由于浮点数精度问题,有时需要使用分数,这个 Fraction 类将会解决这个问题。 (随手写的,如有不足,欢迎指出)
代码如下:
<?php
class Fraction {
public $nume;
public $deno;
private function __construct() {}
private function create1($number) {
if(is_int($number)) {
$this->create2($number,1);
} else if(is_float($number)) {
$this->create2($number * (10 ** 4),10 ** 4);
}
return $this;
}
private function create2($nume,$deno) {
if(is_float($nume) || is_float($deno)) {
$nume = $nume * (10 ** 4);
$deno = $deno * (10 ** 4);
}
$divisor = $this->max_divisor($nume,$deno);
$this->nume = $nume / $divisor;
$this->deno = $deno / $divisor;
return $this;
}
public static function max_divisor($a,$b) {
if($a % $b == 0) {
return $b;
} else {
return self::max_divisor($b,$a % $b);
}
}
public function value() {
return $this->nume / $this->deno;
}
public static function __callStatic($method,$args) {
if($method == 'create') {
$name = $method . count($args);
$obj = new self;
return $obj->$name(...$args);
}
}
public function __toString() {
return $this->nume . '/' . $this->deno;
}
public static function plus(...$numbers) {
$nume = 0;
$deno = 1;
foreach($numbers as $number) {
$number = $number instanceof self ? $number : self::create($number);
$temp = $deno;
$nume *= $number->deno;
$deno *= $number->deno;
$nume = $nume + $number->nume * $temp;
}
return self::create($nume,$deno);
}
public static function subtract(...$numbers) {
$nume = 0;
$deno = 1;
foreach($numbers as $number) {
$number = $number instanceof self ? $number : self::create($number);
$temp = $deno;
$nume *= $number->deno;
$deno *= $number->deno;
$nume = $number->nume * $temp - $nume;
}
return self::create(-$nume,$deno);
}
public static function multiply(...$numbers) {
$nume = 1;
$deno = 1;
foreach($numbers as $number) {
$number = $number instanceof self ? $number : self::create($number);
$nume *= $number->nume;
$deno *= $number->deno;
}
return self::create($nume,$deno);
}
public static function divide(...$numbers) {
$result = $numbers[0];
unset($numbers[0]);
foreach($numbers as $number) {
$number = $number instanceof self ? $number : self::create($number);
$temp = $number->nume;
$number->nume = $number->deno;
$number->deno = $temp;
$result = self::multiply($number,$result);
}
return $result;
}
}
|