-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplexNumbers.php
More file actions
91 lines (68 loc) · 2.68 KB
/
Copy pathcomplexNumbers.php
File metadata and controls
91 lines (68 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
class ComplexNumber{
private float $partReal;
private float $partImaginary;
function __construct(float $partReal, float $partImaginary = 0){
$this->partReal = $partReal;
$this->partImaginary = $partImaginary;
}
public function getStr(): string{
$strImaginary = ($this->partImaginary >= 0) ? '+'. $this->partImaginary : $this->partImaginary;
return $this->partReal. $strImaginary. 'i';
}
public function add(...$terms){
$this->modify('getSum', ...$terms);
}
public function subtract(...$subtrahends){
$this->modify('getDifference', ...$subtrahends);
}
public function multiply(...$factors){
$this->modify('getProduct', ...$factors);
}
public function divide(...$dividers){
$this->modify('getQuotient', ...$dividers);
}
private function getSum(ComplexNumber $term){
$this->partReal += $term->partReal;
$this->partImaginary += $term->partImaginary;
}
private function getDifference(ComplexNumber $subtrahend){
$this->partReal -= $subtrahend->partReal;
$this->partImaginary -= $subtrahend->partImaginary;
}
private function getProduct(ComplexNumber $factor){
$partReal = $this->partReal * $factor->partReal - $this->partImaginary * $factor->partImaginary;
$partImaginary = $this->partReal * $factor->partImaginary + $this->partImaginary * $factor->partReal;
$this->partReal = $partReal;
$this->partImaginary = $partImaginary;
}
private function getQuotient(ComplexNumber $divider){
$sumPow = pow($divider->partReal, 2) + pow($divider->partImaginary, 2);
$partReal = $this->partReal * $divider->partReal + $this->partImaginary * $divider->partImaginary;
$partImaginary = $this->partImaginary * $divider->partReal - $this->partReal * $divider->partImaginary ;
$partReal /= $sumPow;
$partImaginary /= $sumPow;
$this->partReal = $partReal;
$this->partImaginary = $partImaginary;
}
private function modify($callbackModify, ...$args){
$result = $this;
foreach ($args as $arg) {
$arg = self::getValidateType($arg);
$result->$callbackModify($arg);
}
$this->partReal = $result->partReal;
$this->partImaginary = $result->partImaginary;
}
private static function getValidateType($arg): ComplexNumber{
if (!is_object($arg) || !is_a($arg, __CLASS__)){
if (!is_int($arg) && !is_float($arg)) {
throw new TypeError();
}
else{
return new ComplexNumber($arg);
}
}
return $arg;
}
}