PHPExcel
PHPExcel copied to clipboard
SLOPE and INTERCEPT don't trap Divide by Zero
I have a row of cells (B2:F2) that sometimes could be all zero. They are being used as the "known_xs" in =SLOPE(known_ys,known_xs) and =INTERCEPT(known_ys,known_xs) . The "known_ys" (B1:F1) are arbitrary numbers (can be 0, positive, or negative).
Excel gives the expected '#DIV/0!'. PHPExcel gives:
$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('B1','1');
$objPHPExcel->getActiveSheet()->setCellValue('C1','2');
$objPHPExcel->getActiveSheet()->setCellValue('D1','3');
$objPHPExcel->getActiveSheet()->setCellValue('E1','4');
$objPHPExcel->getActiveSheet()->setCellValue('F1','5');
$objPHPExcel->getActiveSheet()->setCellValue('B2','0');
$objPHPExcel->getActiveSheet()->setCellValue('C2','0');
$objPHPExcel->getActiveSheet()->setCellValue('D2','0');
$objPHPExcel->getActiveSheet()->setCellValue('E2','0');
$objPHPExcel->getActiveSheet()->setCellValue('F2','0');
$objPHPExcel->getActiveSheet()->setCellValue('G3', '=SLOPE(B1:F1, B2:F2)');
$objPHPExcel->getActiveSheet()->setCellValue('H3', '=INTERCEPT(B1:F1, B2:F2)');
PHP Warning: Division by zero in Classes/PHPExcel/Shared/trend/bestFitClass.php on line 391, referer: http://mywebsite.html
PHP Warning: Division by zero in Classes/PHPExcel/Shared/trend/bestFitClass.php on line 349, referer: http://mywebsite.html
PHP Warning: Division by zero in Classes/PHPExcel/Shared/trend/bestFitClass.php on line 350, referer: http://mywebsite.html
PHP Warning: Division by zero in Classes/PHPExcel/Shared/trend/bestFitClass.php on line 351, referer: http://mywebsite.html
Same issue if I try to use =IF(COUNTIF( ) ) to avoid the error.
$objPHPExcel->getActiveSheet()->setCellValue("G3", "=IF(COUNTIF(B2:F2, \"=0\")=5, \"DivByZero\", =SLOPE(B1:F1, B2:F2))" );
$objPHPExcel->getActiveSheet()->setCellValue("H3", "=IF(COUNTIF(B2:F2, \"=0\")=5, \"DivByZero\", =INTERCEPT(B1:F1, B2:F2))" );
It would be the same error if the known_xs were all the same number, not necessarily just zero. For all these cases, it's trying to calculate the slope/intercept of a vertical line.
An easier way to test that, would be (with PhpSpreadsheet, but it's mostly same):
var_dump(\PhpOffice\PhpSpreadsheet\Calculation\Statistical::SLOPE([1, 1], [1, 1]));
Would you consider creating a PR for that against PhpSpreadsheet develop branch ?