-
Notifications
You must be signed in to change notification settings - Fork 0
/
Complex.php
80 lines (71 loc) · 2.22 KB
/
Complex.php
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
<?php
Class Complex
{
private function parse($complex)
{
if (!preg_match("/i$/",$complex))
{
$real = (int)$complex;
$imag = 0;
}
else
{
if (!preg_match("/.?\di/",$complex))
{
$complex = preg_replace("/i/","1i",$complex);
}
preg_match_all("/.?\d/", $complex, $m);
if (count($m[0])==1)
{
$real = 0;
$imag = $m[0][0];
}
else
{
$real = $m[0][0];
$imag = $m[0][1];
}
}
#echo "<br>".$real." ".$imag;
return [$real,$imag];
}
private function out_format($real_result,$imag_result)
{
return (($real_result==0) ? "" : $real_result) .
(($imag_result<0 or $real_result=="") ? "" : "+") .
(($imag_result==1)?"":$imag_result) .
"i";
}
public function sum($s1,$s2)
{
list($real1,$imag1) = $this->parse($s1);
list($real2,$imag2) = $this->parse($s2);
$real_result = $real1 + $real2;
$imag_result = $imag1 + $imag2;
return $this->out_format($real_result,$imag_result);
}
public function sub($s1,$s2)
{
list($real1,$imag1) = $this->parse($s1);
list($real2,$imag2) = $this->parse($s2);
$real_result = $real1 - $real2;
$imag_result = $imag1 - $imag2;
return $this->out_format($real_result,$imag_result);
}
public function add($s1,$s2)
{
list($real1,$imag1) = $this->parse($s1);
list($real2,$imag2) = $this->parse($s2);
$real_result = $real1 * $real2 - $imag1 * $imag2;
$imag_result = $real1 * $imag2 + $imag1 * $real2;
return $this->out_format($real_result,$imag_result);
}
public function div($s1,$s2)
{
list($real1,$imag1) = $this->parse($s1);
list($real2,$imag2) = $this->parse($s2);
$real_result = ($real1 * $real2 + $imag1 * $imag2) / (pow($real2,2) + pow($imag2,2));
$imag_result = ($imag1 * $real2 - $real1 * $imag2) / (pow($real2,2) + pow($imag2,2));
return $this->out_format($real_result,$imag_result);
}
}