Does PHP have existing functionality for irregular step ranges, is there a common solution to provide this functionality, or how can the following function be optimized?
The first function is the function I am concerned about. The second function is a real world use case that generates an array to populate values for a function that outputs a select dropdown for HTML.
<?php
function range_multistep($min, $max, Array $steps, $jmp = 10) {
$steps = array_unique($steps);
sort($steps, SORT_NUMERIC);
$bigstep = ($jmp > 0) ? $jmp : $jmp * -1;
$e = ($min > 0) ? floor(log($min, $bigstep)) : 0;
for (; ; $e++) {
foreach ($steps as $step) {
$jump = pow($bigstep, $e);
$num = $step * $jump;
if ($num > $max) {
break 2;
} elseif ($num >= $min) {
$arr[] = $num;
}
}
}
$arr = array_unique($arr);
sort($arr, SORT_NUMERIC);
return $arr;
}
function prices() {
$price_steps = range_multistep(50, 100000, array(5, 10, 25));
$prev_step = 0;
foreach ($price_steps as $price) {
$price_str = '$' . $prev_step . ' - $' . ($price - 1);
$price_arr[] = $price_str;
$prev_step = $price;
}
$price_arr[] = '$' . end($price_steps) . "+";
return $price_arr;
}
print_r(prices());
The result of the previous:
Array
(
[0] => $0 - $49
[1] => $50 - $99
[2] => $100 - $249
[3] => $250 - $499
[4] => $500 - $999
[5] => $1000 - $2499
[6] => $2500 - $4999
[7] => $5000 - $9999
[8] => $10000 - $24999
[9] => $25000 - $49999
[10] => $50000 - $99999
[11] => $100000+
)
Repeated addition is best replaced by multiplication, and repeated multiplication is best replaced by raising to powers -- which you've done.
I see nothing here that requires improvement assuming you don't need "bulletproof" behavior in the face of $jmp = 1 or $min >= $max badly-behaved inputs.
The $e incrementor in the for loop is more of a while(1) endless loop.
So instead misusing the incrementor in pow(), do the pow on your own by just multiplying once per iteration. Calling pow() can be pretty expensive, so doing the pow calculation your own would better distribute the multiplication onto each iteration.
Edit: The following is a variant of your function that distributes the pow() calculation over the iteration. Additionally it does more proper variable initialisation (the return value was not set for example), gives notice if $min and $max are swapped and corrects that, uses abs instead of your ternary, throws an exception if an invalid value was given for log(), renamed some variables and add $num to the return value as key first to spare the array_unique operation at the end:
/**
* #param int $min
* #param int $max
* #param array $steps
* #param int $jmp
* #return array range
*/
function range_multistep($min, $max, Array $steps, $jmp = 10) {
$range = array();
if (!$steps) return $range;
if ($min < $max) {
trigger_error(__FUNCTION__.'(): Minima and Maxima mal-aligned.', E_USER_NOTICE);
list($max, $min) = array($min, $max);
}
$steps = array_unique($steps);
sort($steps, SORT_NUMERIC);
$bigstep = abs($jmp);
if ($bigstep === 0) {
throw new InvalidArgumentException(sprintf('Value %d is invalid for jmp', $jmp));
}
$initExponent = ($min > 0) ? floor(log($min, $bigstep)) : 0;
for ($multiplier = pow($bigstep, $initExponent); ; $multiplier *= $bigstep) {
foreach ($steps as $step) {
$num = $step * $multiplier;
if ($num > $max) {
break 2;
} elseif ($num >= $min) {
$range[$num] = 1;
}
}
}
$range = array_keys($range);
sort($range, SORT_NUMERIC);
return $range;
}
In case you feel experimental, it's also possible to turn the two loops (for+foreach) into one, but the readability of the code does not benefit from it:
for(
$multiplier = pow($bigstep, $initExponent),
$step = reset($steps)
;
$num = $step * $multiplier,
$num <= $max
;
# infinite array iterator:
($step=next($steps))?:
(
$step=reset($steps)
# with reset expression:
AND $multiplier *= $bigstep
)
){
if ($num >= $min)
$range[$num] = 1;
}
I think if you take care to not re-use variables (like the function parameter) and give them better to read names, improvement comes on it's own.
Related
I have an array of numbers like this in PHP:
$numbers = [
0.0021030494216614,
0.0019940179461615,
0.0079320972662613,
0.0040485829959514,
0.0079320972662613,
0.0021030494216614,
0.0019940179461615,
0.0079320972662613,
0.0040485829959514,
0.0079320972662613,
0.0021030494216614,
1.1002979145978,
85.230769230769,
6.5833333333333,
0.015673981191223
];
In PHP, I am trying to find the outliers / anomalies in this array.
As you can see, the anomalies are
1.1002979145978,
85.230769230769,
6.5833333333333,
0.015673981191223
I am trying to find and remove the anomalies in any array.
Here is my code
function remove_anomalies($dataset, $magnitude = 1) {
$count = count($dataset);
$mean = array_sum($dataset) / $count;
$deviation = sqrt(array_sum(array_map("sd_square", $dataset, array_fill(0, $count, $mean))) / $count) * $magnitude;
return array_filter($dataset, function($x) use ($mean, $deviation) { return ($x <= $mean + $deviation && $x >= $mean - $deviation); });
}
function sd_square($x, $mean) {
return pow($x - $mean, 2);
}
However, when I put my array of $numbers in, it only gives me [85.230769230769] as the outlier when there are clearly more outliers there.
I have tried fiddling with the $magnitude and that did not improve anything.
The algorithm shown here uses mean absolute deviation (MAD) a robust measure to identify outliers.
All elements whose distance exceeds a multiple of the MAD are continuously removed and the MAD is recalculated.
function median(array $data)
{
if(($count = count($data)) < 1) return false;
sort($data, SORT_NUMERIC);
$mid = (int)($count/2);
if($count % 2) return $data[$mid];
return ($data[$mid] + $data[$mid-1])/2;
}
function mad(array $data)
{
if(($count = count($data)) < 1) return false;
$median = median($data);
$mad = 0.0;
foreach($data as $xi) {
$mad += abs($xi - $median);
}
return $mad/$count;
}
function cleanMedian(array &$data, $fac = 2.0)
{
do{
$unsetCount = 0;
$median = median($data);
$mad = mad($data) * $fac;
//remove all with diff > $mad
foreach($data as $idx => $val){
if(abs($val - $median) > $mad){
unset($data[$idx]);
++$unsetCount;
}
}
} while($unsetCount > 0);
}
How to use:
$data = [
//..
];
cleanMedian($data);
The parameter $fac needs to be experimented with depending on the data.
With the $ fac = 2 you get the desired result.
array (
0 => 0.0021030494216614,
1 => 0.0019940179461615,
2 => 0.0079320972662613,
3 => 0.0040485829959514,
4 => 0.0079320972662613,
5 => 0.0021030494216614,
6 => 0.0019940179461615,
7 => 0.0079320972662613,
8 => 0.0040485829959514,
9 => 0.0079320972662613,
10 => 0.0021030494216614,
)
With fac = 4, the value 0.015673981191223 is included.
I need to validate that an inputted number is a valid number based on my stepping rules and round up to the nearest valid number if not. These numbers will change but one example would be:
$min = 0.25;
$step = 0.1
$qty = 0.75 // user input
so these would be valid inputs:
0.75
0.85
0.95
But these should round:
0.76 (to 0.85)
0.80 (to 0.85)
I thought I could use modulus somehow but not getting the calculation correct.
if (($qty % min) / $step == 0)) {
echo "good";
}
I've tried some variations of math that are likely very wrong
$step = 0.1;
$min = 0.25;
$qty = .85;
$h = ($qty / $min) / $step;
echo $h;
$j = mround($qty, $min-$step);
echo $j;
function mround($num, $parts) {
if ($parts <= 0) { $parts = 1; }
$res = $num * (1/$parts);
$res = round($res);
return $res /(1/$parts);
}
I think you can use fmod to do this.
$new = $original + ($step - fmod($original - $minimum, $step));
Example on 3v4l.org
I try to recreate what we see when we printing page on office or adobe.
For example, when you want to print page 1 to 5 you write : 1-5 and if you want to print a page outside you write : 1-5,8
At the moment I explode string by ',' :
1-5 / 8
Then explode each result by '-' and if I've got result I loop from first page to last and create variable with comma :
1,2,3,4,5,8
Finally I explode by ',' and use array unique to erase double value.
It take some times to achieve this especially when there's a lot of '-'.
Maybe someone got a easier solution to so this ?
Thank
Edit :
$pages = "1-4,6-8,14,16,18-20";
$pages_explode = explode(',',$pages);
foreach($pages_explode as $page){
$page_explode = explode('-',$page);
if(!empty($page_explode[1])){
for ($i=$page_explode[0]; $i<=$page_explode[1] ; $i++) {
$page_final .= $i.',';
}
}else{
$page_final .= $page_explode[0].',';
}
}
$page_final = explode(',',$page_final);
$page_final = array_unique ($page_final);
foreach($page_final as $value){
echo $value.'<br>';
}
Is it a code golf challenge?
Well a basic approach seems fine to me :
$input = '1-5,6-12,8';
$patterns = explode(',', $input);
$pages = [];
foreach ($patterns as $pattern) {
if (2 == count($range = explode('-', $pattern))) {
$pages = array_merge($pages, range($range[0], $range[1]));
} else {
$pages[] = (int)$pattern;
}
}
$uniquePages = array_unique($pages);
var_dump($uniquePages);
Outputs :
array (size=12)
0 => int 1
1 => int 2
2 => int 3
3 => int 4
4 => int 5
5 => int 6
6 => int 7
7 => int 8
8 => int 9
9 => int 10
10 => int 11
11 => int 12
Having to remove duplicates suggests that you have overlapping ranges in your strings.
Eg: 1-5,2-9,7-15,8,10
You seems to process all these without considering the overlapping areas and finally attempt to remove duplicates by the expensive array_unique function.
Your code should instead remember the minimum and maximum of the resulting range and not process anything that overlaps this range.
Following is a sample code which demonstrates the idea. But its certainly faster than the code you have suggested in your question. You should add parts there to process additional types of delimiters, if any, in your requirement.
<?php
$ranges = "1-5,3-7,6-10,8,11";
$min = 10000;
$max = -1;
$numbers = array(); //Your numbers go here
//Just a utility function to generate numbers from any range and update margins
function generateNumbers($minVal, $maxVal) {
global $min, $max, $numbers;
for ($i = $minVal; $i <= $maxVal; $i++) {
array_push($numbers, $i);
if ($i < $min)
$min = $i;
if ($i > $max)
$max = $i;
}
}
//Seperate ranges
$sets = explode(",", $ranges);
//Go through each range
foreach($sets as $aSet) {
//Extract the range or get individual numbers
$range = explode("-", $aSet);
if (count($range) == 1) { //its an individual number. So check margins and insert
$aSet = intval($aSet);
if ($aSet < $min){
array_push($numbers, $aSet);
$min = $aSet;
}
if ($aSet > $max){
array_push($numbers, $aSet);
$max = $aSet;
}
continue; // <----- For single numbers it ends here
}
//Its a range
$rangeLow = intval($range[0]);
$rangeHigh = intval($range[1]);
//Adjusting numbers to omit cases when ranges fall right on the margins
if ($rangeLow == $min){
$rangeLow++;
}
else
if ($rangeLow == $max) {
$rangeLow--;
}
if ($rangeHigh == $min){
$rangeHigh++;
}
else
if ($rangeHigh == $max) {
$rangeHigh--;
}
//Check if below or above the generated range
if (($rangeLow < $min && $rangeHigh < $min) || ($rangeLow > $max && $rangeHigh > $max)) {
generateNumbers($rangeLow, $rangeHigh);
};
//Check if across the lower edge of the generated range
if ($rangeLow < $min && $rangeHigh > $min && $rangeHigh < $max) {
generateNumbers($rangeLow, $min - 1);
};
//Check if across the upper edge of the generated range
if ($rangeLow > $min && $rangeLow < $max && $rangeHigh > $max) {
generateNumbers($max + 1, $rangeHigh);
};
}
//Now just sort the array
print_r($numbers);
?>
How can I check if a given number is within a range of numbers?
The expression:
($min <= $value) && ($value <= $max)
will be true if $value is between $min and $max, inclusively
See the PHP docs for more on comparison operators
You can use filter_var
filter_var(
$yourInteger,
FILTER_VALIDATE_INT,
array(
'options' => array(
'min_range' => $min,
'max_range' => $max
)
)
);
This will also allow you to specify whether you want to allow octal and hex notation of integers. Note that the function is type-safe. 5.5 is not an integer but a float and will not validate.
Detailed tutorial about filtering data with PHP:
https://phpro.org/tutorials/Filtering-Data-with-PHP.html
Might help:
if ( in_array(2, range(1,7)) ) {
echo 'Number 2 is in range 1-7';
}
http://php.net/manual/en/function.range.php
You could whip up a little helper function to do this:
/**
* Determines if $number is between $min and $max
*
* #param integer $number The number to test
* #param integer $min The minimum value in the range
* #param integer $max The maximum value in the range
* #param boolean $inclusive Whether the range should be inclusive or not
* #return boolean Whether the number was in the range
*/
function in_range($number, $min, $max, $inclusive = FALSE)
{
if (is_int($number) && is_int($min) && is_int($max))
{
return $inclusive
? ($number >= $min && $number <= $max)
: ($number > $min && $number < $max) ;
}
return FALSE;
}
And you would use it like so:
var_dump(in_range(5, 0, 10)); // TRUE
var_dump(in_range(1, 0, 1)); // FALSE
var_dump(in_range(1, 0, 1, TRUE)); // TRUE
var_dump(in_range(11, 0, 10, TRUE)); // FALSE
// etc...
if (($num >= $lower_boundary) && ($num <= $upper_boundary)) {
You may want to adjust the comparison operators if you want the boundary values not to be valid.
You can try the following one-statement:
if (($x-$min)*($x-$max) < 0)
or:
if (max(min($x, $max), $min) == $x)
Some other possibilities:
if (in_array($value, range($min, $max), true)) {
echo "You can be sure that $min <= $value <= $max";
}
Or:
if ($value === min(max($value, $min), $max)) {
echo "You can be sure that $min <= $value <= $max";
}
Actually this is what is use to cast a value which is out of the range to the closest end of it.
$value = min(max($value, $min), $max);
Example
/**
* This is un-sanitized user input.
*/
$posts_per_page = 999;
/**
* Sanitize $posts_per_page.
*/
$posts_per_page = min(max($posts_per_page, 5), 30);
/**
* Use.
*/
var_dump($posts_per_page); // Output: int(30)
using a switch case
switch ($num){
case ($num>= $value1 && $num<= $value2):
echo "within range 1";
break;
case ($num>= $value3 && $num<= $value4):
echo "within range 2";
break;
.
.
.
.
.
default: //default
echo "within no range";
break;
}
I've created a simple helper function.
if ( !function_exists('number_between') )
{
/**
* number_between
*
* #param {integer} $number
* #param {array} $range [min, max]
* #return {boolean}
*/
function number_between(
int $number,
array $range
){
if(
count($range) !== 2 ||
is_numeric($range[0]) === FALSE ||
is_numeric($range[1]) === FALSE
){
throw new \Exception("number_between second parameter must contain two numbers.", E_WARNING);
}
if(
in_array($number, range($range[0], $range[1]))
){
return TRUE;
}else{
return FALSE;
}
}
}
Another way to do this with simple if/else range. For ex:
$watermarkSize = 0;
if (($originalImageWidth >= 0) && ($originalImageWidth <= 640)) {
$watermarkSize = 10;
} else if (($originalImageWidth >= 641) && ($originalImageWidth <= 1024)) {
$watermarkSize = 25;
} else if (($originalImageWidth >= 1025) && ($originalImageWidth <= 2048)) {
$watermarkSize = 50;
} else if (($originalImageWidth >= 2049) && ($originalImageWidth <= 4096)) {
$watermarkSize = 100;
} else {
$watermarkSize = 200;
}
I created a function to check if times in an array overlap somehow:
/**
* Function to check if there are overlapping times in an array of \DateTime objects.
*
* #param $ranges
*
* #return \DateTime[]|bool
*/
public function timesOverlap($ranges) {
foreach ($ranges as $k1 => $t1) {
foreach ($ranges as $k2 => $t2) {
if ($k1 != $k2) {
/* #var \DateTime[] $t1 */
/* #var \DateTime[] $t2 */
$a = $t1[0]->getTimestamp();
$b = $t1[1]->getTimestamp();
$c = $t2[0]->getTimestamp();
$d = $t2[1]->getTimestamp();
if (($c >= $a && $c <= $b) || $d >= $a && $d <= $b) {
return true;
}
}
}
}
return false;
}
Here is my little contribution:
function inRange($number) {
$ranges = [0, 13, 17, 24, 34, 44, 54, 65, 200];
$n = count($ranges);
while($n--){
if( $number > $ranges[$n] )
return $ranges[$n]+1 .'-'. $ranges[$n + 1];
}
I have function for my case
Use:
echo checkRangeNumber(0);
echo checkRangeNumber(1);
echo checkRangeNumber(499);
echo checkRangeNumber(500);
echo checkRangeNumber(501);
echo checkRangeNumber(3001);
echo checkRangeNumber(999);
//return
0
1-500
1-500
1-500
501-1000
3000-3500
501-1000
function checkRangeNumber($number, $per_page = 500)
{
//$per_page = 500; // it's fixed number, but...
if ($number == 0) {
return "0";
}
$num_page = ceil($number / $per_page); // returns 65
$low_limit = ($num_page - 1) * $per_page + 1; // returns 32000
$up_limit = $num_page * $per_page; // returns 40
return "$low_limit-$up_limit";
}
function limit_range($num, $min, $max)
{
// Now limit it
return $num>$max?$max:$num<$min?$min:$num;
}
$min = 0; // Minimum number can be
$max = 4; // Maximum number can be
$num = 10; // Your number
// Number returned is limited to be minimum 0 and maximum 4
echo limit_range($num, $min, $max); // return 4
$num = 2;
echo limit_range($num, $min, $max); // return 2
$num = -1;
echo limit_range($num, $min, $max); // return 0
$ranges = [
1 => [
'min_range' => 0.01,
'max_range' => 199.99
],
2 => [
'min_range' => 200.00,
],
];
foreach($ranges as $value => $range){
if(filter_var($cartTotal, FILTER_VALIDATE_FLOAT, ['options' => $range])){
return $value;
}
}
Thank you so much and I got my answer by adding a break in the foreach loop and now it is working fine.
Here are the updated answer:
foreach ($this->crud->getDataAll('shipping_charges') as $ship) {
if ($weight >= $ship->low && $weight <= $ship->high) {
$val = $ship->amount;
break;
}
else
{
$val = 900;
}
}
echo $val ;
I saw this question,and pop up this idea.
Is there an efficient way to do this in PHP?
EDIT
Best with a demo?
You could use the pear package Math_Matrix for this.
This package claims to be able to do what you are looking for.
There is this open source PHP Library that is able to invert a Matrix.
All you need to do is
<?php
include_once ("Matrix.class.php");
$matrixA = new Matrix(array(array(0, 1), array(2, 6)));
echo $matrixA->getInverse()->getMathMl();
?>
Here tested code https://gist.github.com/unix1/7510208
Only identity_matrix() and invert() functions are enough
Yes there are several ways to accomplish this in php. There are a handful of available libraries. Alternatively, you could maintain your own class and customize as needed. Here is an excerpt from our inhouse library that is based on the mathematical method described in the link. There is a demonstration at the end of the class for further reference.
https://www.intmath.com/matrices-determinants/inverse-matrix-gauss-jordan-elimination.php
class MatrixLibrary
{
//Gauss-Jordan elimination method for matrix inverse
public function inverseMatrix(array $matrix)
{
//TODO $matrix validation
$matrixCount = count($matrix);
$identityMatrix = $this->identityMatrix($matrixCount);
$augmentedMatrix = $this->appendIdentityMatrixToMatrix($matrix, $identityMatrix);
$inverseMatrixWithIdentity = $this->createInverseMatrix($augmentedMatrix);
$inverseMatrix = $this->removeIdentityMatrix($inverseMatrixWithIdentity);
return $inverseMatrix;
}
private function createInverseMatrix(array $matrix)
{
$numberOfRows = count($matrix);
for($i=0; $i<$numberOfRows; $i++)
{
$matrix = $this->oneOperation($matrix, $i, $i);
for($j=0; $j<$numberOfRows; $j++)
{
if($i !== $j)
{
$matrix = $this->zeroOperation($matrix, $j, $i, $i);
}
}
}
$inverseMatrixWithIdentity = $matrix;
return $inverseMatrixWithIdentity;
}
private function oneOperation(array $matrix, $rowPosition, $zeroPosition)
{
if($matrix[$rowPosition][$zeroPosition] !== 1)
{
$numberOfCols = count($matrix[$rowPosition]);
if($matrix[$rowPosition][$zeroPosition] === 0)
{
$divisor = 0.0000000001;
$matrix[$rowPosition][$zeroPosition] = 0.0000000001;
}
else
{
$divisor = $matrix[$rowPosition][$zeroPosition];
}
for($i=0; $i<$numberOfCols; $i++)
{
$matrix[$rowPosition][$i] = $matrix[$rowPosition][$i] / $divisor;
}
}
return $matrix;
}
private function zeroOperation(array $matrix, $rowPosition, $zeroPosition, $subjectRow)
{
$numberOfCols = count($matrix[$rowPosition]);
if($matrix[$rowPosition][$zeroPosition] !== 0)
{
$numberToSubtract = $matrix[$rowPosition][$zeroPosition];
for($i=0; $i<$numberOfCols; $i++)
{
$matrix[$rowPosition][$i] = $matrix[$rowPosition][$i] - $numberToSubtract * $matrix[$subjectRow][$i];
}
}
return $matrix;
}
private function removeIdentityMatrix(array $matrix)
{
$inverseMatrix = array();
$matrixCount = count($matrix);
for($i=0; $i<$matrixCount; $i++)
{
$inverseMatrix[$i] = array_slice($matrix[$i], $matrixCount);
}
return $inverseMatrix;
}
private function appendIdentityMatrixToMatrix(array $matrix, array $identityMatrix)
{
//TODO $matrix & $identityMatrix compliance validation (same number of rows/columns, etc)
$augmentedMatrix = array();
for($i=0; $i<count($matrix); $i++)
{
$augmentedMatrix[$i] = array_merge($matrix[$i], $identityMatrix[$i]);
}
return $augmentedMatrix;
}
public function identityMatrix(int $size)
{
//TODO validate $size
$identityMatrix = array();
for($i=0; $i<$size; $i++)
{
for($j=0; $j<$size; $j++)
{
if($i == $j)
{
$identityMatrix[$i][$j] = 1;
}
else
{
$identityMatrix[$i][$j] = 0;
}
}
}
return $identityMatrix;
}
}
$matrix = array(
array(11, 3, 12),
array(8, 7, 10),
array(13, 14, 15),
);
$matrixLibrary = new MatrixLibrary();
$inverseMatrix = $matrixLibrary->inverseMatrix($matrix);
print_r($inverseMatrix);
/*
Array
(
[0] => Array
(
[0] => 0.33980582524272
[1] => -1.1941747572816
[2] => 0.52427184466019
)
[1] => Array
(
[0] => -0.097087378640777
[1] => -0.087378640776699
[2] => 0.13592233009709
)
[2] => Array
(
[0] => -0.20388349514563
[1] => 1.1165048543689
[2] => -0.51456310679612
)
)
*/
/**
* matrix_inverse
*
* Matrix Inverse
* Guass-Jordan Elimination Method
* Reduced Row Eshelon Form (RREF)
*
* In linear algebra an n-by-n (square) matrix A is called invertible (some
* authors use nonsingular or nondegenerate) if there exists an n-by-n matrix B
* such that AB = BA = In where In denotes the n-by-n identity matrix and the
* multiplication used is ordinary matrix multiplication. If this is the case,
* then the matrix B is uniquely determined by A and is called the inverse of A,
* denoted by A-1. It follows from the theory of matrices that if for finite
* square matrices A and B, then also non-square matrices (m-by-n matrices for
* which m ? n) do not have an inverse. However, in some cases such a matrix may
* have a left inverse or right inverse. If A is m-by-n and the rank of A is
* equal to n, then A has a left inverse: an n-by-m matrix B such that BA = I.
* If A has rank m, then it has a right inverse: an n-by-m matrix B such that
* AB = I.
*
* A square matrix that is not invertible is called singular or degenerate. A
* square matrix is singular if and only if its determinant is 0. Singular
* matrices are rare in the sense that if you pick a random square matrix over
* a continuous uniform distribution on its entries, it will almost surely not
* be singular.
*
* While the most common case is that of matrices over the real or complex
* numbers, all these definitions can be given for matrices over any commutative
* ring. However, in this case the condition for a square matrix to be
* invertible is that its determinant is invertible in the ring, which in
* general is a much stricter requirement than being nonzero. The conditions for
* existence of left-inverse resp. right-inverse are more complicated since a
* notion of rank does not exist over rings.
*/
public function matrix_inverse($m1)
{
$rows = $this->rows($m1);
$cols = $this->columns($m1);
if ($rows != $cols)
{
die("Matrim1 is not square. Can not be inverted.");
}
$m2 = $this->eye($rows);
for ($j = 0; $j < $cols; $j++)
{
$factor = $m1[$j][$j];
if ($this->debug)
{
fms_writeln('Divide Row [' . $j . '] by ' . $m1[$j][$j] . ' (to
give us a "1" in the desired position):');
}
$m1 = $this->rref_div($m1, $j, $factor);
$m2 = $this->rref_div($m2, $j, $factor);
if ($this->debug)
{
$this->disp2($m1, $m2);
}
for ($i = 0; $i < $rows; $i++)
{
if ($i != $j)
{
$factor = $m1[$i][$j];
if ($this->debug)
{
$this->writeln('Row[' . $i . '] - ' . number_format($factor, 4) . ' ×
Row[' . $j . '] (to give us 0 in the desired position):');
}
$m1 = $this->rref_sub($m1, $i, $factor, $j);
$m2 = $this->rref_sub($m2, $i, $factor, $j);
if ($this->debug)
{
$this->disp2($m1, $m2);
}
}
}
}
return $m2;
}