PHP Script for Complex Number Operations
The following is a PHP script for complex number operations. It includes functions for addition, subtraction, multiplication, and division of two complex numbers in rectangular coordinate form. For div($first,$second) function, the $second variable is the divisor. It also includes function that returns the conjugate of a complex number, and a function that converts complex numbers in polar coordinate to rectangular coordinate, and vise versa.
< ?php
function div($first,$second)
{
if(($second['re']==0 && $second['im']==0))
{return(-1);}
$a=$first['re'];
$b=$first['im'];
$c=$second['re'];
$d=$second['im'];
$e=($a*$c)+($b*$d);
$f=($c*$c)+($d*$d);
$g=($b*$c)-($a*$d);
$result['re']=$e/$f;
$result['im']=$g/$f;
return($result);
}function add($first,$second)
{
$result['re']=$first['re']+$second['re'];
$result['im']=$first['im']+$second['im'];
return($result);
}function sub($first,$second)
{
$result['re']=$first['re']-$second['re'];
$result['im']=$first['im']-$second['im'];
return($result);
}function mul($first,$second)
{
$result['re']=($first['re']*$second['re'])-($first['im']*$second['im']);
$result['im']=($first['re']*$second['im'])+($second['re']*$first['im']);
return($result);
}function conj($first)
{
$result['re']=$first['re'];
$result['im']=-1.0*$first['im'];
return($result);
}function rec2pol($first)
{
$result['re']=sqrt(pow($first['re'],2)+pow($first['im'],2));
$result['im']=rad2deg(atan($first['im']/$first['re']));
return($result);
}function pol2rec($first)
{
$result['re']=$first['re']*cos(deg2rad($first['im']));
$result['im']=$first['re']*sin(deg2rad($first['im']));
return($result);
}?>
Filed in: Codes and Scripts











