LibreOffice Module sc (master)  1
interpr5.cxx
Go to the documentation of this file.
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This file is part of the LibreOffice project.
4  *
5  * This Source Code Form is subject to the terms of the Mozilla Public
6  * License, v. 2.0. If a copy of the MPL was not distributed with this
7  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8  *
9  * This file incorporates work covered by the following license notice:
10  *
11  * Licensed to the Apache Software Foundation (ASF) under one or more
12  * contributor license agreements. See the NOTICE file distributed
13  * with this work for additional information regarding copyright
14  * ownership. The ASF licenses this file to you under the Apache
15  * License, Version 2.0 (the "License"); you may not use this file
16  * except in compliance with the License. You may obtain a copy of
17  * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18  */
19 
20 #include <rtl/math.hxx>
21 #include <string.h>
22 #include <math.h>
23 
24 #ifdef DEBUG_SC_LUP_DECOMPOSITION
25 #include <stdio.h>
26 #endif
27 
28 #include <unotools/bootstrap.hxx>
29 #include <svl/zforlist.hxx>
30 
31 #include <interpre.hxx>
32 #include <global.hxx>
33 #include <formulacell.hxx>
34 #include <document.hxx>
35 #include <dociter.hxx>
36 #include <scmatrix.hxx>
37 #include <globstr.hrc>
38 #include <scresid.hxx>
39 #include <cellkeytranslator.hxx>
40 #include <formulagroup.hxx>
41 
42 #include <vector>
43 
44 using ::std::vector;
45 using namespace formula;
46 
47 namespace {
48 
49 struct MatrixAdd
50 {
51  double operator() (const double& lhs, const double& rhs) const
52  {
53  return ::rtl::math::approxAdd( lhs,rhs);
54  }
55 };
56 
57 struct MatrixSub
58 {
59  double operator() (const double& lhs, const double& rhs) const
60  {
61  return ::rtl::math::approxSub( lhs,rhs);
62  }
63 };
64 
65 struct MatrixMul
66 {
67  double operator() (const double& lhs, const double& rhs) const
68  {
69  return lhs * rhs;
70  }
71 };
72 
73 struct MatrixDiv
74 {
75  double operator() (const double& lhs, const double& rhs) const
76  {
77  return ScInterpreter::div( lhs,rhs);
78  }
79 };
80 
81 struct MatrixPow
82 {
83  double operator() (const double& lhs, const double& rhs) const
84  {
85  return ::pow( lhs,rhs);
86  }
87 };
88 
89 // Multiply n x m Mat A with m x l Mat B to n x l Mat R
90 void lcl_MFastMult(const ScMatrixRef& pA, const ScMatrixRef& pB, const ScMatrixRef& pR,
91  SCSIZE n, SCSIZE m, SCSIZE l)
92 {
93  double sum;
94  for (SCSIZE row = 0; row < n; row++)
95  {
96  for (SCSIZE col = 0; col < l; col++)
97  { // result element(col, row) =sum[ (row of A) * (column of B)]
98  sum = 0.0;
99  for (SCSIZE k = 0; k < m; k++)
100  sum += pA->GetDouble(k,row) * pB->GetDouble(col,k);
101  pR->PutDouble(sum, col, row);
102  }
103  }
104 }
105 
106 }
107 
108 double ScInterpreter::ScGetGCD(double fx, double fy)
109 {
110  // By ODFF definition GCD(0,a) => a. This is also vital for the code in
111  // ScGCD() to work correctly with a preset fy=0.0
112  if (fy == 0.0)
113  return fx;
114  else if (fx == 0.0)
115  return fy;
116  else
117  {
118  double fz = fmod(fx, fy);
119  while (fz > 0.0)
120  {
121  fx = fy;
122  fy = fz;
123  fz = fmod(fx, fy);
124  }
125  return fy;
126  }
127 }
128 
130 {
131  short nParamCount = GetByte();
132  if ( !MustHaveParamCountMin( nParamCount, 1 ) )
133  return;
134 
135  double fx, fy = 0.0;
136  ScRange aRange;
137  size_t nRefInList = 0;
138  while (nGlobalError == FormulaError::NONE && nParamCount-- > 0)
139  {
140  switch (GetStackType())
141  {
142  case svDouble :
143  case svString:
144  case svSingleRef:
145  {
146  fx = ::rtl::math::approxFloor( GetDouble());
147  if (fx < 0.0)
148  {
149  PushIllegalArgument();
150  return;
151  }
152  fy = ScGetGCD(fx, fy);
153  }
154  break;
155  case svDoubleRef :
156  case svRefList :
157  {
158  FormulaError nErr = FormulaError::NONE;
159  PopDoubleRef( aRange, nParamCount, nRefInList);
160  double nCellVal;
161  ScValueIterator aValIter( mrDoc, aRange, mnSubTotalFlags );
162  if (aValIter.GetFirst(nCellVal, nErr))
163  {
164  do
165  {
166  fx = ::rtl::math::approxFloor( nCellVal);
167  if (fx < 0.0)
168  {
169  PushIllegalArgument();
170  return;
171  }
172  fy = ScGetGCD(fx, fy);
173  } while (nErr == FormulaError::NONE && aValIter.GetNext(nCellVal, nErr));
174  }
175  SetError(nErr);
176  }
177  break;
178  case svMatrix :
179  case svExternalSingleRef:
180  case svExternalDoubleRef:
181  {
182  ScMatrixRef pMat = GetMatrix();
183  if (pMat)
184  {
185  SCSIZE nC, nR;
186  pMat->GetDimensions(nC, nR);
187  if (nC == 0 || nR == 0)
188  SetError(FormulaError::IllegalArgument);
189  else
190  {
191  double nVal = pMat->GetGcd();
192  fy = ScGetGCD(nVal,fy);
193  }
194  }
195  }
196  break;
197  default : SetError(FormulaError::IllegalParameter); break;
198  }
199  }
200  PushDouble(fy);
201 }
202 
204 {
205  short nParamCount = GetByte();
206  if ( !MustHaveParamCountMin( nParamCount, 1 ) )
207  return;
208 
209  double fx, fy = 1.0;
210  ScRange aRange;
211  size_t nRefInList = 0;
212  while (nGlobalError == FormulaError::NONE && nParamCount-- > 0)
213  {
214  switch (GetStackType())
215  {
216  case svDouble :
217  case svString:
218  case svSingleRef:
219  {
220  fx = ::rtl::math::approxFloor( GetDouble());
221  if (fx < 0.0)
222  {
223  PushIllegalArgument();
224  return;
225  }
226  if (fx == 0.0 || fy == 0.0)
227  fy = 0.0;
228  else
229  fy = fx * fy / ScGetGCD(fx, fy);
230  }
231  break;
232  case svDoubleRef :
233  case svRefList :
234  {
235  FormulaError nErr = FormulaError::NONE;
236  PopDoubleRef( aRange, nParamCount, nRefInList);
237  double nCellVal;
238  ScValueIterator aValIter( mrDoc, aRange, mnSubTotalFlags );
239  if (aValIter.GetFirst(nCellVal, nErr))
240  {
241  do
242  {
243  fx = ::rtl::math::approxFloor( nCellVal);
244  if (fx < 0.0)
245  {
246  PushIllegalArgument();
247  return;
248  }
249  if (fx == 0.0 || fy == 0.0)
250  fy = 0.0;
251  else
252  fy = fx * fy / ScGetGCD(fx, fy);
253  } while (nErr == FormulaError::NONE && aValIter.GetNext(nCellVal, nErr));
254  }
255  SetError(nErr);
256  }
257  break;
258  case svMatrix :
259  case svExternalSingleRef:
260  case svExternalDoubleRef:
261  {
262  ScMatrixRef pMat = GetMatrix();
263  if (pMat)
264  {
265  SCSIZE nC, nR;
266  pMat->GetDimensions(nC, nR);
267  if (nC == 0 || nR == 0)
268  SetError(FormulaError::IllegalArgument);
269  else
270  {
271  double nVal = pMat->GetLcm();
272  fy = (nVal * fy ) / ScGetGCD(nVal, fy);
273  }
274  }
275  }
276  break;
277  default : SetError(FormulaError::IllegalParameter); break;
278  }
279  }
280  PushDouble(fy);
281 }
282 
284 {
285  rMat->SetErrorInterpreter( this);
286  // A temporary matrix is mutable and ScMatrix::CloneIfConst() returns the
287  // very matrix.
288  rMat->SetMutable();
289  SCSIZE nCols, nRows;
290  rMat->GetDimensions( nCols, nRows);
291  if ( nCols != nC || nRows != nR )
292  { // arbitrary limit of elements exceeded
293  SetError( FormulaError::MatrixSize);
294  rMat.reset();
295  }
296 }
297 
299 {
300  ScMatrixRef pMat;
301  if (bEmpty)
302  pMat = new ScMatrix(nC, nR);
303  else
304  pMat = new ScMatrix(nC, nR, 0.0);
305  MakeMatNew(pMat, nC, nR);
306  return pMat;
307 }
308 
309 ScMatrixRef ScInterpreter::GetNewMat(SCSIZE nC, SCSIZE nR, const std::vector<double>& rValues)
310 {
311  ScMatrixRef pMat(new ScMatrix(nC, nR, rValues));
312  MakeMatNew(pMat, nC, nR);
313  return pMat;
314 }
315 
317  SCCOL nCol1, SCROW nRow1, SCTAB nTab1,
318  SCCOL nCol2, SCROW nRow2, SCTAB nTab2 )
319 {
320  if (nTab1 != nTab2 || nGlobalError != FormulaError::NONE)
321  {
322  // Not a 2D matrix.
323  SetError(FormulaError::IllegalParameter);
324  return nullptr;
325  }
326 
327  if (nTab1 == nTab2 && pToken)
328  {
329  const ScComplexRefData& rCRef = *pToken->GetDoubleRef();
330  if (rCRef.IsTrimToData())
331  {
332  // Clamp the size of the matrix area to rows which actually contain data.
333  // For e.g. SUM(IF over an entire column, this can make a big difference,
334  // But lets not trim the empty space from the top or left as this matters
335  // at least in matrix formulas involving IF().
336  // Refer ScCompiler::AnnotateTrimOnDoubleRefs() where double-refs are
337  // flagged for trimming.
338  SCCOL nTempCol = nCol1;
339  SCROW nTempRow = nRow1;
340  mrDoc.ShrinkToDataArea(nTab1, nTempCol, nTempRow, nCol2, nRow2);
341  }
342  }
343 
344  SCSIZE nMatCols = static_cast<SCSIZE>(nCol2 - nCol1 + 1);
345  SCSIZE nMatRows = static_cast<SCSIZE>(nRow2 - nRow1 + 1);
346 
347  if (!ScMatrix::IsSizeAllocatable( nMatCols, nMatRows))
348  {
349  SetError(FormulaError::MatrixSize);
350  return nullptr;
351  }
352 
353  ScTokenMatrixMap::const_iterator aIter;
354  if (pToken && pTokenMatrixMap && ((aIter = pTokenMatrixMap->find( pToken)) != pTokenMatrixMap->end()))
355  {
356  /* XXX casting const away here is ugly; ScMatrixToken (to which the
357  * result of this function usually is assigned) should not be forced to
358  * carry a ScConstMatrixRef though.
359  * TODO: a matrix already stored in pTokenMatrixMap should be
360  * read-only and have a copy-on-write mechanism. Previously all tokens
361  * were modifiable so we're already better than before ... */
362  return const_cast<FormulaToken*>((*aIter).second.get())->GetMatrix();
363  }
364 
365  ScMatrixRef pMat = GetNewMat( nMatCols, nMatRows, true);
366  if (!pMat || nGlobalError != FormulaError::NONE)
367  return nullptr;
368 
369  if (!bCalcAsShown)
370  {
371  // Use fast array fill.
372  mrDoc.FillMatrix(*pMat, nTab1, nCol1, nRow1, nCol2, nRow2);
373  }
374  else
375  {
376  // Use slower ScCellIterator to round values.
377 
378  // TODO: this probably could use CellBucket for faster storage, see
379  // sc/source/core/data/column2.cxx and FillMatrixHandler, and then be
380  // moved to a function on its own, and/or squeeze the rounding into a
381  // similar FillMatrixHandler that would need to keep track of the cell
382  // position then.
383 
384  // Set position where the next entry is expected.
385  SCROW nNextRow = nRow1;
386  SCCOL nNextCol = nCol1;
387  // Set last position as if there was a previous entry.
388  SCROW nThisRow = nRow2;
389  SCCOL nThisCol = nCol1 - 1;
390 
391  ScCellIterator aCellIter( mrDoc, ScRange( nCol1, nRow1, nTab1, nCol2, nRow2, nTab2));
392  for (bool bHas = aCellIter.first(); bHas; bHas = aCellIter.next())
393  {
394  nThisCol = aCellIter.GetPos().Col();
395  nThisRow = aCellIter.GetPos().Row();
396  if (nThisCol != nNextCol || nThisRow != nNextRow)
397  {
398  // Fill empty between iterator's positions.
399  for ( ; nNextCol <= nThisCol; ++nNextCol)
400  {
401  const SCSIZE nC = nNextCol - nCol1;
402  const SCSIZE nMatStopRow = ((nNextCol < nThisCol) ? nMatRows : nThisRow - nRow1);
403  for (SCSIZE nR = nNextRow - nRow1; nR < nMatStopRow; ++nR)
404  {
405  pMat->PutEmpty( nC, nR);
406  }
407  nNextRow = nRow1;
408  }
409  }
410  if (nThisRow == nRow2)
411  {
412  nNextCol = nThisCol + 1;
413  nNextRow = nRow1;
414  }
415  else
416  {
417  nNextCol = nThisCol;
418  nNextRow = nThisRow + 1;
419  }
420 
421  const SCSIZE nMatCol = static_cast<SCSIZE>(nThisCol - nCol1);
422  const SCSIZE nMatRow = static_cast<SCSIZE>(nThisRow - nRow1);
423  ScRefCellValue aCell( aCellIter.getRefCellValue());
424  if (aCellIter.isEmpty() || aCell.hasEmptyValue())
425  {
426  pMat->PutEmpty( nMatCol, nMatRow);
427  }
428  else if (aCell.hasError())
429  {
430  pMat->PutError( aCell.mpFormula->GetErrCode(), nMatCol, nMatRow);
431  }
432  else if (aCell.hasNumeric())
433  {
434  double fVal = aCell.getValue();
435  // CELLTYPE_FORMULA already stores the rounded value.
436  if (aCell.meType == CELLTYPE_VALUE)
437  {
438  // TODO: this could be moved to ScCellIterator to take
439  // advantage of the faster ScAttrArray_IterGetNumberFormat.
440  const ScAddress aAdr( nThisCol, nThisRow, nTab1);
441  const sal_uInt32 nNumFormat = mrDoc.GetNumberFormat( mrContext, aAdr);
442  fVal = mrDoc.RoundValueAsShown( fVal, nNumFormat, &mrContext);
443  }
444  pMat->PutDouble( fVal, nMatCol, nMatRow);
445  }
446  else if (aCell.hasString())
447  {
448  pMat->PutString( mrStrPool.intern( aCell.getString(&mrDoc)), nMatCol, nMatRow);
449  }
450  else
451  {
452  assert(!"aCell.what?");
453  pMat->PutEmpty( nMatCol, nMatRow);
454  }
455  }
456 
457  // Fill empty if iterator's last position wasn't the end.
458  if (nThisCol != nCol2 || nThisRow != nRow2)
459  {
460  for ( ; nNextCol <= nCol2; ++nNextCol)
461  {
462  SCSIZE nC = nNextCol - nCol1;
463  for (SCSIZE nR = nNextRow - nRow1; nR < nMatRows; ++nR)
464  {
465  pMat->PutEmpty( nC, nR);
466  }
467  nNextRow = nRow1;
468  }
469  }
470  }
471 
472  if (pToken && pTokenMatrixMap)
473  pTokenMatrixMap->emplace(pToken, new ScMatrixToken( pMat));
474 
475  return pMat;
476 }
477 
479 {
480  ScMatrixRef pMat = nullptr;
481  switch (GetRawStackType())
482  {
483  case svSingleRef :
484  {
485  ScAddress aAdr;
486  PopSingleRef( aAdr );
487  pMat = GetNewMat(1, 1);
488  if (pMat)
489  {
490  ScRefCellValue aCell(mrDoc, aAdr);
491  if (aCell.hasEmptyValue())
492  pMat->PutEmpty(0, 0);
493  else if (aCell.hasNumeric())
494  pMat->PutDouble(GetCellValue(aAdr, aCell), 0);
495  else
496  {
498  GetCellString(aStr, aCell);
499  pMat->PutString(aStr, 0);
500  }
501  }
502  }
503  break;
504  case svDoubleRef:
505  {
506  SCCOL nCol1, nCol2;
507  SCROW nRow1, nRow2;
508  SCTAB nTab1, nTab2;
509  const formula::FormulaToken* p = sp ? pStack[sp-1] : nullptr;
510  PopDoubleRef(nCol1, nRow1, nTab1, nCol2, nRow2, nTab2);
511  pMat = CreateMatrixFromDoubleRef( p, nCol1, nRow1, nTab1,
512  nCol2, nRow2, nTab2);
513  }
514  break;
515  case svMatrix:
516  pMat = PopMatrix();
517  break;
518  case svError :
519  case svMissing :
520  case svDouble :
521  {
522  double fVal = GetDouble();
523  pMat = GetNewMat( 1, 1);
524  if ( pMat )
525  {
526  if ( nGlobalError != FormulaError::NONE )
527  {
528  fVal = CreateDoubleError( nGlobalError);
529  nGlobalError = FormulaError::NONE;
530  }
531  pMat->PutDouble( fVal, 0);
532  }
533  }
534  break;
535  case svString :
536  {
538  pMat = GetNewMat( 1, 1);
539  if ( pMat )
540  {
541  if ( nGlobalError != FormulaError::NONE )
542  {
543  double fVal = CreateDoubleError( nGlobalError);
544  pMat->PutDouble( fVal, 0);
545  nGlobalError = FormulaError::NONE;
546  }
547  else
548  pMat->PutString(aStr, 0);
549  }
550  }
551  break;
552  case svExternalSingleRef:
553  {
555  PopExternalSingleRef(pToken);
556  pMat = GetNewMat( 1, 1, true);
557  if (!pMat)
558  break;
559  if (nGlobalError != FormulaError::NONE)
560  {
561  pMat->PutError( nGlobalError, 0, 0);
562  nGlobalError = FormulaError::NONE;
563  break;
564  }
565  switch (pToken->GetType())
566  {
567  case svError:
568  pMat->PutError( pToken->GetError(), 0, 0);
569  break;
570  case svDouble:
571  pMat->PutDouble( pToken->GetDouble(), 0, 0);
572  break;
573  case svString:
574  pMat->PutString( pToken->GetString(), 0, 0);
575  break;
576  default:
577  ; // nothing, empty element matrix
578  }
579  }
580  break;
581  case svExternalDoubleRef:
582  PopExternalDoubleRef(pMat);
583  break;
584  default:
585  PopError();
586  SetError( FormulaError::IllegalArgument);
587  break;
588  }
589  return pMat;
590 }
591 
592 ScMatrixRef ScInterpreter::GetMatrix( short & rParam, size_t & rRefInList )
593 {
594  switch (GetRawStackType())
595  {
596  case svRefList:
597  {
599  PopDoubleRef( aRange, rParam, rRefInList);
600  if (nGlobalError != FormulaError::NONE)
601  return nullptr;
602 
603  SCCOL nCol1, nCol2;
604  SCROW nRow1, nRow2;
605  SCTAB nTab1, nTab2;
606  aRange.GetVars( nCol1, nRow1, nTab1, nCol2, nRow2, nTab2);
607  return CreateMatrixFromDoubleRef( nullptr, nCol1, nRow1, nTab1, nCol2, nRow2, nTab2);
608  }
609  break;
610  default:
611  return GetMatrix();
612  }
613 }
614 
616 {
617  sc::RangeMatrix aRet;
618  switch (GetRawStackType())
619  {
620  case svMatrix:
621  aRet = PopRangeMatrix();
622  break;
623  default:
624  aRet.mpMat = GetMatrix();
625  }
626  return aRet;
627 }
628 
630 {
631  if ( !MustHaveParamCount( GetByte(), 3 ) )
632  return;
633 
634  // 0 to count-1
635  // Theoretically we could have GetSize() instead of GetUInt32(), but
636  // really, practically ...
637  SCSIZE nR = static_cast<SCSIZE>(GetUInt32());
638  SCSIZE nC = static_cast<SCSIZE>(GetUInt32());
639  if (nGlobalError != FormulaError::NONE)
640  {
641  PushError( nGlobalError);
642  return;
643  }
644  switch (GetStackType())
645  {
646  case svSingleRef :
647  {
648  ScAddress aAdr;
649  PopSingleRef( aAdr );
650  ScRefCellValue aCell(mrDoc, aAdr);
651  if (aCell.meType == CELLTYPE_FORMULA)
652  {
653  FormulaError nErrCode = aCell.mpFormula->GetErrCode();
654  if (nErrCode != FormulaError::NONE)
655  PushError( nErrCode);
656  else
657  {
658  const ScMatrix* pMat = aCell.mpFormula->GetMatrix();
659  CalculateMatrixValue(pMat,nC,nR);
660  }
661  }
662  else
663  PushIllegalParameter();
664  }
665  break;
666  case svDoubleRef :
667  {
668  SCCOL nCol1;
669  SCROW nRow1;
670  SCTAB nTab1;
671  SCCOL nCol2;
672  SCROW nRow2;
673  SCTAB nTab2;
674  PopDoubleRef(nCol1, nRow1, nTab1, nCol2, nRow2, nTab2);
675  if (nCol2 - nCol1 >= static_cast<SCCOL>(nR) &&
676  nRow2 - nRow1 >= static_cast<SCROW>(nC) &&
677  nTab1 == nTab2)
678  {
679  ScAddress aAdr( sal::static_int_cast<SCCOL>( nCol1 + nR ),
680  sal::static_int_cast<SCROW>( nRow1 + nC ), nTab1 );
681  ScRefCellValue aCell(mrDoc, aAdr);
682  if (aCell.hasNumeric())
683  PushDouble(GetCellValue(aAdr, aCell));
684  else
685  {
687  GetCellString(aStr, aCell);
688  PushString(aStr);
689  }
690  }
691  else
692  PushNoValue();
693  }
694  break;
695  case svMatrix:
696  {
697  ScMatrixRef pMat = PopMatrix();
698  CalculateMatrixValue(pMat.get(),nC,nR);
699  }
700  break;
701  default:
702  PopError();
703  PushIllegalParameter();
704  break;
705  }
706 }
708 {
709  if (pMat)
710  {
711  SCSIZE nCl, nRw;
712  pMat->GetDimensions(nCl, nRw);
713  if (nC < nCl && nR < nRw)
714  {
715  const ScMatrixValue nMatVal = pMat->Get( nC, nR);
716  ScMatValType nMatValType = nMatVal.nType;
717  if (ScMatrix::IsNonValueType( nMatValType))
718  PushString( nMatVal.GetString() );
719  else
720  PushDouble(nMatVal.fVal);
721  // also handles DoubleError
722  }
723  else
724  PushNoValue();
725  }
726  else
727  PushNoValue();
728 }
729 
731 {
732  if ( !MustHaveParamCount( GetByte(), 1 ) )
733  return;
734 
735  SCSIZE nDim = static_cast<SCSIZE>(GetUInt32());
736  if (nGlobalError != FormulaError::NONE || nDim == 0)
737  PushIllegalArgument();
738  else if (!ScMatrix::IsSizeAllocatable( nDim, nDim))
739  PushError( FormulaError::MatrixSize);
740  else
741  {
742  ScMatrixRef pRMat = GetNewMat(nDim, nDim);
743  if (pRMat)
744  {
745  MEMat(pRMat, nDim);
746  PushMatrix(pRMat);
747  }
748  else
749  PushIllegalArgument();
750  }
751 }
752 
754 {
755  mM->FillDouble(0.0, 0, 0, n-1, n-1);
756  for (SCSIZE i = 0; i < n; i++)
757  mM->PutDouble(1.0, i, i);
758 }
759 
760 /* Matrix LUP decomposition according to the pseudocode of "Introduction to
761  * Algorithms" by Cormen, Leiserson, Rivest, Stein.
762  *
763  * Added scaling for numeric stability.
764  *
765  * Given an n x n nonsingular matrix A, find a permutation matrix P, a unit
766  * lower-triangular matrix L, and an upper-triangular matrix U such that PA=LU.
767  * Compute L and U "in place" in the matrix A, the original content is
768  * destroyed. Note that the diagonal elements of the U triangular matrix
769  * replace the diagonal elements of the L-unit matrix (that are each ==1). The
770  * permutation matrix P is an array, where P[i]=j means that the i-th row of P
771  * contains a 1 in column j. Additionally keep track of the number of
772  * permutations (row exchanges).
773  *
774  * Returns 0 if a singular matrix is encountered, else +1 if an even number of
775  * permutations occurred, or -1 if odd, which is the sign of the determinant.
776  * This may be used to calculate the determinant by multiplying the sign with
777  * the product of the diagonal elements of the LU matrix.
778  */
779 static int lcl_LUP_decompose( ScMatrix* mA, const SCSIZE n,
780  ::std::vector< SCSIZE> & P )
781 {
782  int nSign = 1;
783  // Find scale of each row.
784  ::std::vector< double> aScale(n);
785  for (SCSIZE i=0; i < n; ++i)
786  {
787  double fMax = 0.0;
788  for (SCSIZE j=0; j < n; ++j)
789  {
790  double fTmp = fabs( mA->GetDouble( j, i));
791  if (fMax < fTmp)
792  fMax = fTmp;
793  }
794  if (fMax == 0.0)
795  return 0; // singular matrix
796  aScale[i] = 1.0 / fMax;
797  }
798  // Represent identity permutation, P[i]=i
799  for (SCSIZE i=0; i < n; ++i)
800  P[i] = i;
801  // "Recursion" on the diagonal.
802  SCSIZE l = n - 1;
803  for (SCSIZE k=0; k < l; ++k)
804  {
805  // Implicit pivoting. With the scale found for a row, compare values of
806  // a column and pick largest.
807  double fMax = 0.0;
808  double fScale = aScale[k];
809  SCSIZE kp = k;
810  for (SCSIZE i = k; i < n; ++i)
811  {
812  double fTmp = fScale * fabs( mA->GetDouble( k, i));
813  if (fMax < fTmp)
814  {
815  fMax = fTmp;
816  kp = i;
817  }
818  }
819  if (fMax == 0.0)
820  return 0; // singular matrix
821  // Swap rows. The pivot element will be at mA[k,kp] (row,col notation)
822  if (k != kp)
823  {
824  // permutations
825  SCSIZE nTmp = P[k];
826  P[k] = P[kp];
827  P[kp] = nTmp;
828  nSign = -nSign;
829  // scales
830  double fTmp = aScale[k];
831  aScale[k] = aScale[kp];
832  aScale[kp] = fTmp;
833  // elements
834  for (SCSIZE i=0; i < n; ++i)
835  {
836  double fMatTmp = mA->GetDouble( i, k);
837  mA->PutDouble( mA->GetDouble( i, kp), i, k);
838  mA->PutDouble( fMatTmp, i, kp);
839  }
840  }
841  // Compute Schur complement.
842  for (SCSIZE i = k+1; i < n; ++i)
843  {
844  double fNum = mA->GetDouble( k, i);
845  double fDen = mA->GetDouble( k, k);
846  mA->PutDouble( fNum/fDen, k, i);
847  for (SCSIZE j = k+1; j < n; ++j)
848  mA->PutDouble( ( mA->GetDouble( j, i) * fDen -
849  fNum * mA->GetDouble( j, k) ) / fDen, j, i);
850  }
851  }
852 #ifdef DEBUG_SC_LUP_DECOMPOSITION
853  fprintf( stderr, "\n%s\n", "lcl_LUP_decompose(): LU");
854  for (SCSIZE i=0; i < n; ++i)
855  {
856  for (SCSIZE j=0; j < n; ++j)
857  fprintf( stderr, "%8.2g ", mA->GetDouble( j, i));
858  fprintf( stderr, "\n%s\n", "");
859  }
860  fprintf( stderr, "\n%s\n", "lcl_LUP_decompose(): P");
861  for (SCSIZE j=0; j < n; ++j)
862  fprintf( stderr, "%5u ", (unsigned)P[j]);
863  fprintf( stderr, "\n%s\n", "");
864 #endif
865 
866  bool bSingular=false;
867  for (SCSIZE i=0; i<n && !bSingular; i++)
868  bSingular = (mA->GetDouble(i,i)) == 0.0;
869  if (bSingular)
870  nSign = 0;
871 
872  return nSign;
873 }
874 
875 /* Solve a LUP decomposed equation Ax=b. LU is a combined matrix of L and U
876  * triangulars and P the permutation vector as obtained from
877  * lcl_LUP_decompose(). B is the right-hand side input vector, X is used to
878  * return the solution vector.
879  */
880 static void lcl_LUP_solve( const ScMatrix* mLU, const SCSIZE n,
881  const ::std::vector< SCSIZE> & P, const ::std::vector< double> & B,
882  ::std::vector< double> & X )
883 {
884  SCSIZE nFirst = SCSIZE_MAX;
885  // Ax=b => PAx=Pb, with decomposition LUx=Pb.
886  // Define y=Ux and solve for y in Ly=Pb using forward substitution.
887  for (SCSIZE i=0; i < n; ++i)
888  {
889  double fSum = B[P[i]];
890  // Matrix inversion comes with a lot of zeros in the B vectors, we
891  // don't have to do all the computing with results multiplied by zero.
892  // Until then, simply lookout for the position of the first nonzero
893  // value.
894  if (nFirst != SCSIZE_MAX)
895  {
896  for (SCSIZE j = nFirst; j < i; ++j)
897  fSum -= mLU->GetDouble( j, i) * X[j]; // X[j] === y[j]
898  }
899  else if (fSum)
900  nFirst = i;
901  X[i] = fSum; // X[i] === y[i]
902  }
903  // Solve for x in Ux=y using back substitution.
904  for (SCSIZE i = n; i--; )
905  {
906  double fSum = X[i]; // X[i] === y[i]
907  for (SCSIZE j = i+1; j < n; ++j)
908  fSum -= mLU->GetDouble( j, i) * X[j]; // X[j] === x[j]
909  X[i] = fSum / mLU->GetDouble( i, i); // X[i] === x[i]
910  }
911 #ifdef DEBUG_SC_LUP_DECOMPOSITION
912  fprintf( stderr, "\n%s\n", "lcl_LUP_solve():");
913  for (SCSIZE i=0; i < n; ++i)
914  fprintf( stderr, "%8.2g ", X[i]);
915  fprintf( stderr, "%s\n", "");
916 #endif
917 }
918 
920 {
921  if ( !MustHaveParamCount( GetByte(), 1 ) )
922  return;
923 
924  ScMatrixRef pMat = GetMatrix();
925  if (!pMat)
926  {
927  PushIllegalParameter();
928  return;
929  }
930  if ( !pMat->IsNumeric() )
931  {
932  PushNoValue();
933  return;
934  }
935  SCSIZE nC, nR;
936  pMat->GetDimensions(nC, nR);
937  if ( nC != nR || nC == 0 )
938  PushIllegalArgument();
939  else if (!ScMatrix::IsSizeAllocatable( nC, nR))
940  PushError( FormulaError::MatrixSize);
941  else
942  {
943  // LUP decomposition is done inplace, use copy.
944  ScMatrixRef xLU = pMat->Clone();
945  if (!xLU)
946  PushError( FormulaError::CodeOverflow);
947  else
948  {
949  ::std::vector< SCSIZE> P(nR);
950  int nDetSign = lcl_LUP_decompose( xLU.get(), nR, P);
951  if (!nDetSign)
952  PushInt(0); // singular matrix
953  else
954  {
955  // In an LU matrix the determinant is simply the product of
956  // all diagonal elements.
957  double fDet = nDetSign;
958  for (SCSIZE i=0; i < nR; ++i)
959  fDet *= xLU->GetDouble( i, i);
960  PushDouble( fDet);
961  }
962  }
963  }
964 }
965 
967 {
968  if ( !MustHaveParamCount( GetByte(), 1 ) )
969  return;
970 
971  ScMatrixRef pMat = GetMatrix();
972  if (!pMat)
973  {
974  PushIllegalParameter();
975  return;
976  }
977  if ( !pMat->IsNumeric() )
978  {
979  PushNoValue();
980  return;
981  }
982  SCSIZE nC, nR;
983  pMat->GetDimensions(nC, nR);
984 
986  {
988  if (pInterpreter != nullptr)
989  {
990  ScMatrixRef xResMat = pInterpreter->inverseMatrix(*pMat);
991  if (xResMat)
992  {
993  PushMatrix(xResMat);
994  return;
995  }
996  }
997  }
998 
999  if ( nC != nR || nC == 0 )
1000  PushIllegalArgument();
1001  else if (!ScMatrix::IsSizeAllocatable( nC, nR))
1002  PushError( FormulaError::MatrixSize);
1003  else
1004  {
1005  // LUP decomposition is done inplace, use copy.
1006  ScMatrixRef xLU = pMat->Clone();
1007  // The result matrix.
1008  ScMatrixRef xY = GetNewMat( nR, nR);
1009  if (!xLU || !xY)
1010  PushError( FormulaError::CodeOverflow);
1011  else
1012  {
1013  ::std::vector< SCSIZE> P(nR);
1014  int nDetSign = lcl_LUP_decompose( xLU.get(), nR, P);
1015  if (!nDetSign)
1016  PushIllegalArgument();
1017  else
1018  {
1019  // Solve equation for each column.
1020  ::std::vector< double> B(nR);
1021  ::std::vector< double> X(nR);
1022  for (SCSIZE j=0; j < nR; ++j)
1023  {
1024  for (SCSIZE i=0; i < nR; ++i)
1025  B[i] = 0.0;
1026  B[j] = 1.0;
1027  lcl_LUP_solve( xLU.get(), nR, P, B, X);
1028  for (SCSIZE i=0; i < nR; ++i)
1029  xY->PutDouble( X[i], j, i);
1030  }
1031 #ifdef DEBUG_SC_LUP_DECOMPOSITION
1032  /* Possible checks for ill-condition:
1033  * 1. Scale matrix, invert scaled matrix. If there are
1034  * elements of the inverted matrix that are several
1035  * orders of magnitude greater than 1 =>
1036  * ill-conditioned.
1037  * Just how much is "several orders"?
1038  * 2. Invert the inverted matrix and assess whether the
1039  * result is sufficiently close to the original matrix.
1040  * If not => ill-conditioned.
1041  * Just what is sufficient?
1042  * 3. Multiplying the inverse by the original matrix should
1043  * produce a result sufficiently close to the identity
1044  * matrix.
1045  * Just what is sufficient?
1046  *
1047  * The following is #3.
1048  */
1049  const double fInvEpsilon = 1.0E-7;
1050  ScMatrixRef xR = GetNewMat( nR, nR);
1051  if (xR)
1052  {
1053  ScMatrix* pR = xR.get();
1054  lcl_MFastMult( pMat, xY.get(), pR, nR, nR, nR);
1055  fprintf( stderr, "\n%s\n", "ScMatInv(): mult-identity");
1056  for (SCSIZE i=0; i < nR; ++i)
1057  {
1058  for (SCSIZE j=0; j < nR; ++j)
1059  {
1060  double fTmp = pR->GetDouble( j, i);
1061  fprintf( stderr, "%8.2g ", fTmp);
1062  if (fabs( fTmp - (i == j)) > fInvEpsilon)
1063  SetError( FormulaError::IllegalArgument);
1064  }
1065  fprintf( stderr, "\n%s\n", "");
1066  }
1067  }
1068 #endif
1069  if (nGlobalError != FormulaError::NONE)
1070  PushError( nGlobalError);
1071  else
1072  PushMatrix( xY);
1073  }
1074  }
1075  }
1076 }
1077 
1079 {
1080  if ( !MustHaveParamCount( GetByte(), 2 ) )
1081  return;
1082 
1083  ScMatrixRef pMat2 = GetMatrix();
1084  ScMatrixRef pMat1 = GetMatrix();
1085  ScMatrixRef pRMat;
1086  if (pMat1 && pMat2)
1087  {
1088  if ( pMat1->IsNumeric() && pMat2->IsNumeric() )
1089  {
1090  SCSIZE nC1, nC2;
1091  SCSIZE nR1, nR2;
1092  pMat1->GetDimensions(nC1, nR1);
1093  pMat2->GetDimensions(nC2, nR2);
1094  if (nC1 != nR2)
1095  PushIllegalArgument();
1096  else
1097  {
1098  pRMat = GetNewMat(nC2, nR1);
1099  if (pRMat)
1100  {
1101  double sum;
1102  for (SCSIZE i = 0; i < nR1; i++)
1103  {
1104  for (SCSIZE j = 0; j < nC2; j++)
1105  {
1106  sum = 0.0;
1107  for (SCSIZE k = 0; k < nC1; k++)
1108  {
1109  sum += pMat1->GetDouble(k,i)*pMat2->GetDouble(j,k);
1110  }
1111  pRMat->PutDouble(sum, j, i);
1112  }
1113  }
1114  PushMatrix(pRMat);
1115  }
1116  else
1117  PushIllegalArgument();
1118  }
1119  }
1120  else
1121  PushNoValue();
1122  }
1123  else
1124  PushIllegalParameter();
1125 }
1126 
1128 {
1129  if ( !MustHaveParamCount( GetByte(), 1 ) )
1130  return;
1131 
1132  ScMatrixRef pMat = GetMatrix();
1133  ScMatrixRef pRMat;
1134  if (pMat)
1135  {
1136  SCSIZE nC, nR;
1137  pMat->GetDimensions(nC, nR);
1138  pRMat = GetNewMat(nR, nC);
1139  if ( pRMat )
1140  {
1141  pMat->MatTrans(*pRMat);
1142  PushMatrix(pRMat);
1143  }
1144  else
1145  PushIllegalArgument();
1146  }
1147  else
1148  PushIllegalParameter();
1149 }
1150 
1156 {
1157  if (n1 == 1)
1158  return n2;
1159  else if (n2 == 1)
1160  return n1;
1161  else if (n1 < n2)
1162  return n1;
1163  else
1164  return n2;
1165 }
1166 
1167 template<class Function>
1169  const ScMatrix& rMat1, const ScMatrix& rMat2, ScInterpreter* pInterpreter)
1170 {
1171  static const Function Op;
1172 
1173  SCSIZE nC1, nC2, nMinC;
1174  SCSIZE nR1, nR2, nMinR;
1175  SCSIZE i, j;
1176  rMat1.GetDimensions(nC1, nR1);
1177  rMat2.GetDimensions(nC2, nR2);
1178  nMinC = lcl_GetMinExtent( nC1, nC2);
1179  nMinR = lcl_GetMinExtent( nR1, nR2);
1180  ScMatrixRef xResMat = pInterpreter->GetNewMat(nMinC, nMinR);
1181  if (xResMat)
1182  {
1183  for (i = 0; i < nMinC; i++)
1184  {
1185  for (j = 0; j < nMinR; j++)
1186  {
1187  bool bVal1 = rMat1.IsValueOrEmpty(i,j);
1188  bool bVal2 = rMat2.IsValueOrEmpty(i,j);
1189  FormulaError nErr;
1190  if (bVal1 && bVal2)
1191  {
1192  double d = Op(rMat1.GetDouble(i,j), rMat2.GetDouble(i,j));
1193  xResMat->PutDouble( d, i, j);
1194  }
1195  else if (((nErr = rMat1.GetErrorIfNotString(i,j)) != FormulaError::NONE) ||
1196  ((nErr = rMat2.GetErrorIfNotString(i,j)) != FormulaError::NONE))
1197  {
1198  xResMat->PutError( nErr, i, j);
1199  }
1200  else if ((!bVal1 && rMat1.IsStringOrEmpty(i,j)) || (!bVal2 && rMat2.IsStringOrEmpty(i,j)))
1201  {
1202  FormulaError nError1 = FormulaError::NONE;
1203  SvNumFormatType nFmt1 = SvNumFormatType::ALL;
1204  double fVal1 = (bVal1 ? rMat1.GetDouble(i,j) :
1205  pInterpreter->ConvertStringToValue( rMat1.GetString(i,j).getString(), nError1, nFmt1));
1206 
1207  FormulaError nError2 = FormulaError::NONE;
1208  SvNumFormatType nFmt2 = SvNumFormatType::ALL;
1209  double fVal2 = (bVal2 ? rMat2.GetDouble(i,j) :
1210  pInterpreter->ConvertStringToValue( rMat2.GetString(i,j).getString(), nError2, nFmt2));
1211 
1212  if (nError1 != FormulaError::NONE)
1213  xResMat->PutError( nError1, i, j);
1214  else if (nError2 != FormulaError::NONE)
1215  xResMat->PutError( nError2, i, j);
1216  else
1217  {
1218  double d = Op( fVal1, fVal2);
1219  xResMat->PutDouble( d, i, j);
1220  }
1221  }
1222  else
1223  xResMat->PutError( FormulaError::NoValue, i, j);
1224  }
1225  }
1226  }
1227  return xResMat;
1228 }
1229 
1231 {
1232  SCSIZE nC1, nC2, nMinC;
1233  SCSIZE nR1, nR2, nMinR;
1234  pMat1->GetDimensions(nC1, nR1);
1235  pMat2->GetDimensions(nC2, nR2);
1236  nMinC = lcl_GetMinExtent( nC1, nC2);
1237  nMinR = lcl_GetMinExtent( nR1, nR2);
1238  ScMatrixRef xResMat = GetNewMat(nMinC, nMinR);
1239  if (xResMat)
1240  {
1241  xResMat->MatConcat(nMinC, nMinR, pMat1, pMat2, *pFormatter, mrDoc.GetSharedStringPool());
1242  }
1243  return xResMat;
1244 }
1245 
1246 // for DATE, TIME, DATETIME, DURATION
1248 {
1249  if ( nFmt1 == SvNumFormatType::UNDEFINED && nFmt2 == SvNumFormatType::UNDEFINED )
1250  return;
1251 
1252  if ( nFmt1 == nFmt2 )
1253  {
1254  if ( nFmt1 == SvNumFormatType::TIME || nFmt1 == SvNumFormatType::DATETIME
1255  || nFmt1 == SvNumFormatType::DURATION )
1256  nFuncFmt = SvNumFormatType::DURATION; // times result in time duration
1257  // else: nothing special, number (date - date := days)
1258  }
1259  else if ( nFmt1 == SvNumFormatType::UNDEFINED )
1260  nFuncFmt = nFmt2; // e.g. date + days := date
1261  else if ( nFmt2 == SvNumFormatType::UNDEFINED )
1262  nFuncFmt = nFmt1;
1263  else
1264  {
1265  if ( nFmt1 == SvNumFormatType::DATE || nFmt2 == SvNumFormatType::DATE ||
1266  nFmt1 == SvNumFormatType::DATETIME || nFmt2 == SvNumFormatType::DATETIME )
1267  {
1268  if ( nFmt1 == SvNumFormatType::TIME || nFmt2 == SvNumFormatType::TIME )
1269  nFuncFmt = SvNumFormatType::DATETIME; // date + time
1270  }
1271  }
1272 }
1273 
1275 {
1276  CalculateAddSub(false);
1277 }
1278 
1280 {
1281  ScMatrixRef pMat1 = nullptr;
1282  ScMatrixRef pMat2 = nullptr;
1283  double fVal1 = 0.0, fVal2 = 0.0;
1284  SvNumFormatType nFmt1, nFmt2;
1285  nFmt1 = nFmt2 = SvNumFormatType::UNDEFINED;
1286  SvNumFormatType nFmtCurrencyType = nCurFmtType;
1287  sal_uLong nFmtCurrencyIndex = nCurFmtIndex;
1288  SvNumFormatType nFmtPercentType = nCurFmtType;
1289  if ( GetStackType() == svMatrix )
1290  pMat2 = GetMatrix();
1291  else
1292  {
1293  fVal2 = GetDouble();
1294  switch ( nCurFmtType )
1295  {
1296  case SvNumFormatType::DATE :
1297  case SvNumFormatType::TIME :
1298  case SvNumFormatType::DATETIME :
1299  case SvNumFormatType::DURATION :
1300  nFmt2 = nCurFmtType;
1301  break;
1302  case SvNumFormatType::CURRENCY :
1303  nFmtCurrencyType = nCurFmtType;
1304  nFmtCurrencyIndex = nCurFmtIndex;
1305  break;
1306  case SvNumFormatType::PERCENT :
1307  nFmtPercentType = SvNumFormatType::PERCENT;
1308  break;
1309  default: break;
1310  }
1311  }
1312  if ( GetStackType() == svMatrix )
1313  pMat1 = GetMatrix();
1314  else
1315  {
1316  fVal1 = GetDouble();
1317  switch ( nCurFmtType )
1318  {
1319  case SvNumFormatType::DATE :
1320  case SvNumFormatType::TIME :
1321  case SvNumFormatType::DATETIME :
1322  case SvNumFormatType::DURATION :
1323  nFmt1 = nCurFmtType;
1324  break;
1325  case SvNumFormatType::CURRENCY :
1326  nFmtCurrencyType = nCurFmtType;
1327  nFmtCurrencyIndex = nCurFmtIndex;
1328  break;
1329  case SvNumFormatType::PERCENT :
1330  nFmtPercentType = SvNumFormatType::PERCENT;
1331  break;
1332  default: break;
1333  }
1334  }
1335  if (pMat1 && pMat2)
1336  {
1337  ScMatrixRef pResMat;
1338  if ( _bSub )
1339  {
1340  pResMat = lcl_MatrixCalculation<MatrixSub>( *pMat1, *pMat2, this);
1341  }
1342  else
1343  {
1344  pResMat = lcl_MatrixCalculation<MatrixAdd>( *pMat1, *pMat2, this);
1345  }
1346 
1347  if (!pResMat)
1348  PushNoValue();
1349  else
1350  PushMatrix(pResMat);
1351  }
1352  else if (pMat1 || pMat2)
1353  {
1354  double fVal;
1355  bool bFlag;
1356  ScMatrixRef pMat = pMat1;
1357  if (!pMat)
1358  {
1359  fVal = fVal1;
1360  pMat = pMat2;
1361  bFlag = true; // double - Matrix
1362  }
1363  else
1364  {
1365  fVal = fVal2;
1366  bFlag = false; // Matrix - double
1367  }
1368  SCSIZE nC, nR;
1369  pMat->GetDimensions(nC, nR);
1370  ScMatrixRef pResMat = GetNewMat(nC, nR, true);
1371  if (pResMat)
1372  {
1373  if (_bSub)
1374  {
1375  pMat->SubOp( bFlag, fVal, *pResMat);
1376  }
1377  else
1378  {
1379  pMat->AddOp( fVal, *pResMat);
1380  }
1381  PushMatrix(pResMat);
1382  }
1383  else
1384  PushIllegalArgument();
1385  }
1386  else
1387  {
1388  // Determine nFuncFmtType type before PushDouble().
1389  if ( nFmtCurrencyType == SvNumFormatType::CURRENCY )
1390  {
1391  nFuncFmtType = nFmtCurrencyType;
1392  nFuncFmtIndex = nFmtCurrencyIndex;
1393  }
1394  else
1395  {
1396  lcl_GetDiffDateTimeFmtType( nFuncFmtType, nFmt1, nFmt2 );
1397  if (nFmtPercentType == SvNumFormatType::PERCENT && nFuncFmtType == SvNumFormatType::NUMBER)
1398  nFuncFmtType = SvNumFormatType::PERCENT;
1399  }
1400  if ( _bSub )
1401  PushDouble( ::rtl::math::approxSub( fVal1, fVal2 ) );
1402  else
1403  PushDouble( ::rtl::math::approxAdd( fVal1, fVal2 ) );
1404  }
1405 }
1406 
1408 {
1409  ScMatrixRef pMat1 = nullptr;
1410  ScMatrixRef pMat2 = nullptr;
1411  OUString sStr1, sStr2;
1412  if ( GetStackType() == svMatrix )
1413  pMat2 = GetMatrix();
1414  else
1415  sStr2 = GetString().getString();
1416  if ( GetStackType() == svMatrix )
1417  pMat1 = GetMatrix();
1418  else
1419  sStr1 = GetString().getString();
1420  if (pMat1 && pMat2)
1421  {
1422  ScMatrixRef pResMat = MatConcat(pMat1, pMat2);
1423  if (!pResMat)
1424  PushNoValue();
1425  else
1426  PushMatrix(pResMat);
1427  }
1428  else if (pMat1 || pMat2)
1429  {
1430  OUString sStr;
1431  bool bFlag;
1432  ScMatrixRef pMat = pMat1;
1433  if (!pMat)
1434  {
1435  sStr = sStr1;
1436  pMat = pMat2;
1437  bFlag = true; // double - Matrix
1438  }
1439  else
1440  {
1441  sStr = sStr2;
1442  bFlag = false; // Matrix - double
1443  }
1444  SCSIZE nC, nR;
1445  pMat->GetDimensions(nC, nR);
1446  ScMatrixRef pResMat = GetNewMat(nC, nR);
1447  if (pResMat)
1448  {
1449  if (nGlobalError != FormulaError::NONE)
1450  {
1451  for (SCSIZE i = 0; i < nC; ++i)
1452  for (SCSIZE j = 0; j < nR; ++j)
1453  pResMat->PutError( nGlobalError, i, j);
1454  }
1455  else if (bFlag)
1456  {
1457  for (SCSIZE i = 0; i < nC; ++i)
1458  for (SCSIZE j = 0; j < nR; ++j)
1459  {
1460  FormulaError nErr = pMat->GetErrorIfNotString( i, j);
1461  if (nErr != FormulaError::NONE)
1462  pResMat->PutError( nErr, i, j);
1463  else
1464  {
1465  OUString aTmp = sStr + pMat->GetString(*pFormatter, i, j).getString();
1466  pResMat->PutString(mrStrPool.intern(aTmp), i, j);
1467  }
1468  }
1469  }
1470  else
1471  {
1472  for (SCSIZE i = 0; i < nC; ++i)
1473  for (SCSIZE j = 0; j < nR; ++j)
1474  {
1475  FormulaError nErr = pMat->GetErrorIfNotString( i, j);
1476  if (nErr != FormulaError::NONE)
1477  pResMat->PutError( nErr, i, j);
1478  else
1479  {
1480  OUString aTmp = pMat->GetString(*pFormatter, i, j).getString() + sStr;
1481  pResMat->PutString(mrStrPool.intern(aTmp), i, j);
1482  }
1483  }
1484  }
1485  PushMatrix(pResMat);
1486  }
1487  else
1488  PushIllegalArgument();
1489  }
1490  else
1491  {
1492  if ( CheckStringResultLen( sStr1, sStr2 ) )
1493  sStr1 += sStr2;
1494  PushString(sStr1);
1495  }
1496 }
1497 
1499 {
1500  CalculateAddSub(true);
1501 }
1502 
1504 {
1505  ScMatrixRef pMat1 = nullptr;
1506  ScMatrixRef pMat2 = nullptr;
1507  double fVal1 = 0.0, fVal2 = 0.0;
1508  SvNumFormatType nFmtCurrencyType = nCurFmtType;
1509  sal_uLong nFmtCurrencyIndex = nCurFmtIndex;
1510  if ( GetStackType() == svMatrix )
1511  pMat2 = GetMatrix();
1512  else
1513  {
1514  fVal2 = GetDouble();
1515  switch ( nCurFmtType )
1516  {
1517  case SvNumFormatType::CURRENCY :
1518  nFmtCurrencyType = nCurFmtType;
1519  nFmtCurrencyIndex = nCurFmtIndex;
1520  break;
1521  default: break;
1522  }
1523  }
1524  if ( GetStackType() == svMatrix )
1525  pMat1 = GetMatrix();
1526  else
1527  {
1528  fVal1 = GetDouble();
1529  switch ( nCurFmtType )
1530  {
1531  case SvNumFormatType::CURRENCY :
1532  nFmtCurrencyType = nCurFmtType;
1533  nFmtCurrencyIndex = nCurFmtIndex;
1534  break;
1535  default: break;
1536  }
1537  }
1538  if (pMat1 && pMat2)
1539  {
1540  ScMatrixRef pResMat = lcl_MatrixCalculation<MatrixMul>( *pMat1, *pMat2, this);
1541  if (!pResMat)
1542  PushNoValue();
1543  else
1544  PushMatrix(pResMat);
1545  }
1546  else if (pMat1 || pMat2)
1547  {
1548  double fVal;
1549  ScMatrixRef pMat = pMat1;
1550  if (!pMat)
1551  {
1552  fVal = fVal1;
1553  pMat = pMat2;
1554  }
1555  else
1556  fVal = fVal2;
1557  SCSIZE nC, nR;
1558  pMat->GetDimensions(nC, nR);
1559  ScMatrixRef pResMat = GetNewMat(nC, nR);
1560  if (pResMat)
1561  {
1562  pMat->MulOp( fVal, *pResMat);
1563  PushMatrix(pResMat);
1564  }
1565  else
1566  PushIllegalArgument();
1567  }
1568  else
1569  {
1570  // Determine nFuncFmtType type before PushDouble().
1571  if ( nFmtCurrencyType == SvNumFormatType::CURRENCY )
1572  {
1573  nFuncFmtType = nFmtCurrencyType;
1574  nFuncFmtIndex = nFmtCurrencyIndex;
1575  }
1576  PushDouble(fVal1 * fVal2);
1577  }
1578 }
1579 
1581 {
1582  ScMatrixRef pMat1 = nullptr;
1583  ScMatrixRef pMat2 = nullptr;
1584  double fVal1 = 0.0, fVal2 = 0.0;
1585  SvNumFormatType nFmtCurrencyType = nCurFmtType;
1586  sal_uLong nFmtCurrencyIndex = nCurFmtIndex;
1587  SvNumFormatType nFmtCurrencyType2 = SvNumFormatType::UNDEFINED;
1588  if ( GetStackType() == svMatrix )
1589  pMat2 = GetMatrix();
1590  else
1591  {
1592  fVal2 = GetDouble();
1593  // do not take over currency, 123kg/456USD is not USD
1594  nFmtCurrencyType2 = nCurFmtType;
1595  }
1596  if ( GetStackType() == svMatrix )
1597  pMat1 = GetMatrix();
1598  else
1599  {
1600  fVal1 = GetDouble();
1601  switch ( nCurFmtType )
1602  {
1603  case SvNumFormatType::CURRENCY :
1604  nFmtCurrencyType = nCurFmtType;
1605  nFmtCurrencyIndex = nCurFmtIndex;
1606  break;
1607  default: break;
1608  }
1609  }
1610  if (pMat1 && pMat2)
1611  {
1612  ScMatrixRef pResMat = lcl_MatrixCalculation<MatrixDiv>( *pMat1, *pMat2, this);
1613  if (!pResMat)
1614  PushNoValue();
1615  else
1616  PushMatrix(pResMat);
1617  }
1618  else if (pMat1 || pMat2)
1619  {
1620  double fVal;
1621  bool bFlag;
1622  ScMatrixRef pMat = pMat1;
1623  if (!pMat)
1624  {
1625  fVal = fVal1;
1626  pMat = pMat2;
1627  bFlag = true; // double - Matrix
1628  }
1629  else
1630  {
1631  fVal = fVal2;
1632  bFlag = false; // Matrix - double
1633  }
1634  SCSIZE nC, nR;
1635  pMat->GetDimensions(nC, nR);
1636  ScMatrixRef pResMat = GetNewMat(nC, nR);
1637  if (pResMat)
1638  {
1639  pMat->DivOp( bFlag, fVal, *pResMat);
1640  PushMatrix(pResMat);
1641  }
1642  else
1643  PushIllegalArgument();
1644  }
1645  else
1646  {
1647  // Determine nFuncFmtType type before PushDouble().
1648  if ( nFmtCurrencyType == SvNumFormatType::CURRENCY &&
1649  nFmtCurrencyType2 != SvNumFormatType::CURRENCY)
1650  { // even USD/USD is not USD
1651  nFuncFmtType = nFmtCurrencyType;
1652  nFuncFmtIndex = nFmtCurrencyIndex;
1653  }
1654  PushDouble( div( fVal1, fVal2) );
1655  }
1656 }
1657 
1659 {
1660  if ( MustHaveParamCount( GetByte(), 2 ) )
1661  ScPow();
1662 }
1663 
1665 {
1666  ScMatrixRef pMat1 = nullptr;
1667  ScMatrixRef pMat2 = nullptr;
1668  double fVal1 = 0.0, fVal2 = 0.0;
1669  if ( GetStackType() == svMatrix )
1670  pMat2 = GetMatrix();
1671  else
1672  fVal2 = GetDouble();
1673  if ( GetStackType() == svMatrix )
1674  pMat1 = GetMatrix();
1675  else
1676  fVal1 = GetDouble();
1677  if (pMat1 && pMat2)
1678  {
1679  ScMatrixRef pResMat = lcl_MatrixCalculation<MatrixPow>( *pMat1, *pMat2, this);
1680  if (!pResMat)
1681  PushNoValue();
1682  else
1683  PushMatrix(pResMat);
1684  }
1685  else if (pMat1 || pMat2)
1686  {
1687  double fVal;
1688  bool bFlag;
1689  ScMatrixRef pMat = pMat1;
1690  if (!pMat)
1691  {
1692  fVal = fVal1;
1693  pMat = pMat2;
1694  bFlag = true; // double - Matrix
1695  }
1696  else
1697  {
1698  fVal = fVal2;
1699  bFlag = false; // Matrix - double
1700  }
1701  SCSIZE nC, nR;
1702  pMat->GetDimensions(nC, nR);
1703  ScMatrixRef pResMat = GetNewMat(nC, nR);
1704  if (pResMat)
1705  {
1706  pMat->PowOp( bFlag, fVal, *pResMat);
1707  PushMatrix(pResMat);
1708  }
1709  else
1710  PushIllegalArgument();
1711  }
1712  else
1713  {
1714  PushDouble( sc::power( fVal1, fVal2));
1715  }
1716 }
1717 
1718 namespace {
1719 
1720 class SumValues
1721 {
1722  double mfSum;
1723  bool mbError;
1724 public:
1725  SumValues() : mfSum(0.0), mbError(false) {}
1726 
1727  void operator() (double f)
1728  {
1729  if (mbError)
1730  return;
1731 
1733  if (nErr == FormulaError::NONE)
1734  mfSum += f;
1735  else if (nErr != FormulaError::ElementNaN)
1736  {
1737  // Propagate the first error encountered, ignore "this is not a
1738  // number" elements.
1739  mfSum = f;
1740  mbError = true;
1741  }
1742  }
1743 
1744  double getValue() const { return mfSum; }
1745 };
1746 
1747 }
1748 
1750 {
1751  short nParamCount = GetByte();
1752  if ( !MustHaveParamCountMin( nParamCount, 1) )
1753  return;
1754 
1755  // XXX NOTE: Excel returns #VALUE! for reference list and 0 (why?) for
1756  // array of references. We calculate the proper individual arrays if sizes
1757  // match.
1758 
1759  size_t nInRefList = 0;
1760  ScMatrixRef pMatLast;
1761  ScMatrixRef pMat;
1762 
1763  pMatLast = GetMatrix( --nParamCount, nInRefList);
1764  if (!pMatLast)
1765  {
1766  PushIllegalParameter();
1767  return;
1768  }
1769 
1770  SCSIZE nC, nCLast, nR, nRLast;
1771  pMatLast->GetDimensions(nCLast, nRLast);
1772  std::vector<double> aResArray;
1773  pMatLast->GetDoubleArray(aResArray);
1774 
1775  while (nParamCount--)
1776  {
1777  pMat = GetMatrix( nParamCount, nInRefList);
1778  if (!pMat)
1779  {
1780  PushIllegalParameter();
1781  return;
1782  }
1783  pMat->GetDimensions(nC, nR);
1784  if (nC != nCLast || nR != nRLast)
1785  {
1786  PushNoValue();
1787  return;
1788  }
1789 
1790  pMat->MergeDoubleArrayMultiply(aResArray);
1791  }
1792 
1793  double fSum = std::for_each(aResArray.begin(), aResArray.end(), SumValues()).getValue();
1794  PushDouble(fSum);
1795 }
1796 
1798 {
1799  CalculateSumX2MY2SumX2DY2(false);
1800 }
1802 {
1803  if ( !MustHaveParamCount( GetByte(), 2 ) )
1804  return;
1805 
1806  ScMatrixRef pMat1 = nullptr;
1807  ScMatrixRef pMat2 = nullptr;
1808  SCSIZE i, j;
1809  pMat2 = GetMatrix();
1810  pMat1 = GetMatrix();
1811  if (!pMat2 || !pMat1)
1812  {
1813  PushIllegalParameter();
1814  return;
1815  }
1816  SCSIZE nC1, nC2;
1817  SCSIZE nR1, nR2;
1818  pMat2->GetDimensions(nC2, nR2);
1819  pMat1->GetDimensions(nC1, nR1);
1820  if (nC1 != nC2 || nR1 != nR2)
1821  {
1822  PushNoValue();
1823  return;
1824  }
1825  double fVal, fSum = 0.0;
1826  for (i = 0; i < nC1; i++)
1827  for (j = 0; j < nR1; j++)
1828  if (!pMat1->IsStringOrEmpty(i,j) && !pMat2->IsStringOrEmpty(i,j))
1829  {
1830  fVal = pMat1->GetDouble(i,j);
1831  fSum += fVal * fVal;
1832  fVal = pMat2->GetDouble(i,j);
1833  if ( _bSumX2DY2 )
1834  fSum += fVal * fVal;
1835  else
1836  fSum -= fVal * fVal;
1837  }
1838  PushDouble(fSum);
1839 }
1840 
1842 {
1843  CalculateSumX2MY2SumX2DY2(true);
1844 }
1845 
1847 {
1848  if ( !MustHaveParamCount( GetByte(), 2 ) )
1849  return;
1850 
1851  ScMatrixRef pMat2 = GetMatrix();
1852  ScMatrixRef pMat1 = GetMatrix();
1853  if (!pMat2 || !pMat1)
1854  {
1855  PushIllegalParameter();
1856  return;
1857  }
1858  SCSIZE nC1, nC2;
1859  SCSIZE nR1, nR2;
1860  pMat2->GetDimensions(nC2, nR2);
1861  pMat1->GetDimensions(nC1, nR1);
1862  if (nC1 != nC2 || nR1 != nR2)
1863  {
1864  PushNoValue();
1865  return;
1866  } // if (nC1 != nC2 || nR1 != nR2)
1867  ScMatrixRef pResMat = lcl_MatrixCalculation<MatrixSub>( *pMat1, *pMat2, this);
1868  if (!pResMat)
1869  {
1870  PushNoValue();
1871  }
1872  else
1873  {
1874  ScMatrix::IterateResult aRes = pResMat->SumSquare(false);
1875  double fSum = aRes.mfFirst + aRes.mfRest;
1876  PushDouble(fSum);
1877  }
1878 }
1879 
1881 {
1882  if ( !MustHaveParamCount( GetByte(), 2 ) )
1883  return;
1884 
1885  vector<double> aBinArray;
1886  vector<tools::Long> aBinIndexOrder;
1887 
1888  GetSortArray( 1, aBinArray, &aBinIndexOrder, false, false );
1889  SCSIZE nBinSize = aBinArray.size();
1890  if (nGlobalError != FormulaError::NONE)
1891  {
1892  PushNoValue();
1893  return;
1894  }
1895 
1896  vector<double> aDataArray;
1897  GetSortArray( 1, aDataArray, nullptr, false, false );
1898  SCSIZE nDataSize = aDataArray.size();
1899 
1900  if (aDataArray.empty() || nGlobalError != FormulaError::NONE)
1901  {
1902  PushNoValue();
1903  return;
1904  }
1905  ScMatrixRef pResMat = GetNewMat(1, nBinSize+1);
1906  if (!pResMat)
1907  {
1908  PushIllegalArgument();
1909  return;
1910  }
1911 
1912  if (nBinSize != aBinIndexOrder.size())
1913  {
1914  PushIllegalArgument();
1915  return;
1916  }
1917 
1918  SCSIZE j;
1919  SCSIZE i = 0;
1920  for (j = 0; j < nBinSize; ++j)
1921  {
1922  SCSIZE nCount = 0;
1923  while (i < nDataSize && aDataArray[i] <= aBinArray[j])
1924  {
1925  ++nCount;
1926  ++i;
1927  }
1928  pResMat->PutDouble(static_cast<double>(nCount), aBinIndexOrder[j]);
1929  }
1930  pResMat->PutDouble(static_cast<double>(nDataSize-i), j);
1931  PushMatrix(pResMat);
1932 }
1933 
1934 namespace {
1935 
1936 // Helper methods for LINEST/LOGEST and TREND/GROWTH
1937 // All matrices must already exist and have the needed size, no control tests
1938 // done. Those methods, which names start with lcl_T, are adapted to case 3,
1939 // where Y (=observed values) is given as row.
1940 // Remember, ScMatrix matrices are zero based, index access (column,row).
1941 
1942 // <A;B> over all elements; uses the matrices as vectors of length M
1943 double lcl_GetSumProduct(const ScMatrixRef& pMatA, const ScMatrixRef& pMatB, SCSIZE nM)
1944 {
1945  double fSum = 0.0;
1946  for (SCSIZE i=0; i<nM; i++)
1947  fSum += pMatA->GetDouble(i) * pMatB->GetDouble(i);
1948  return fSum;
1949 }
1950 
1951 // Special version for use within QR decomposition.
1952 // Euclidean norm of column index C starting in row index R;
1953 // matrix A has count N rows.
1954 double lcl_GetColumnEuclideanNorm(const ScMatrixRef& pMatA, SCSIZE nC, SCSIZE nR, SCSIZE nN)
1955 {
1956  double fNorm = 0.0;
1957  for (SCSIZE row=nR; row<nN; row++)
1958  fNorm += (pMatA->GetDouble(nC,row)) * (pMatA->GetDouble(nC,row));
1959  return sqrt(fNorm);
1960 }
1961 
1962 // Euclidean norm of row index R starting in column index C;
1963 // matrix A has count N columns.
1964 double lcl_TGetColumnEuclideanNorm(const ScMatrixRef& pMatA, SCSIZE nR, SCSIZE nC, SCSIZE nN)
1965 {
1966  double fNorm = 0.0;
1967  for (SCSIZE col=nC; col<nN; col++)
1968  fNorm += (pMatA->GetDouble(col,nR)) * (pMatA->GetDouble(col,nR));
1969  return sqrt(fNorm);
1970 }
1971 
1972 // Special version for use within QR decomposition.
1973 // Maximum norm of column index C starting in row index R;
1974 // matrix A has count N rows.
1975 double lcl_GetColumnMaximumNorm(const ScMatrixRef& pMatA, SCSIZE nC, SCSIZE nR, SCSIZE nN)
1976 {
1977  double fNorm = 0.0;
1978  for (SCSIZE row=nR; row<nN; row++)
1979  {
1980  double fVal = fabs(pMatA->GetDouble(nC,row));
1981  if (fNorm < fVal)
1982  fNorm = fVal;
1983  }
1984  return fNorm;
1985 }
1986 
1987 // Maximum norm of row index R starting in col index C;
1988 // matrix A has count N columns.
1989 double lcl_TGetColumnMaximumNorm(const ScMatrixRef& pMatA, SCSIZE nR, SCSIZE nC, SCSIZE nN)
1990 {
1991  double fNorm = 0.0;
1992  for (SCSIZE col=nC; col<nN; col++)
1993  {
1994  double fVal = fabs(pMatA->GetDouble(col,nR));
1995  if (fNorm < fVal)
1996  fNorm = fVal;
1997  }
1998  return fNorm;
1999 }
2000 
2001 // Special version for use within QR decomposition.
2002 // <A(Ca);B(Cb)> starting in row index R;
2003 // Ca and Cb are indices of columns, matrices A and B have count N rows.
2004 double lcl_GetColumnSumProduct(const ScMatrixRef& pMatA, SCSIZE nCa,
2005  const ScMatrixRef& pMatB, SCSIZE nCb, SCSIZE nR, SCSIZE nN)
2006 {
2007  double fResult = 0.0;
2008  for (SCSIZE row=nR; row<nN; row++)
2009  fResult += pMatA->GetDouble(nCa,row) * pMatB->GetDouble(nCb,row);
2010  return fResult;
2011 }
2012 
2013 // <A(Ra);B(Rb)> starting in column index C;
2014 // Ra and Rb are indices of rows, matrices A and B have count N columns.
2015 double lcl_TGetColumnSumProduct(const ScMatrixRef& pMatA, SCSIZE nRa,
2016  const ScMatrixRef& pMatB, SCSIZE nRb, SCSIZE nC, SCSIZE nN)
2017 {
2018  double fResult = 0.0;
2019  for (SCSIZE col=nC; col<nN; col++)
2020  fResult += pMatA->GetDouble(col,nRa) * pMatB->GetDouble(col,nRb);
2021  return fResult;
2022 }
2023 
2024 // no mathematical signum, but used to switch between adding and subtracting
2025 double lcl_GetSign(double fValue)
2026 {
2027  return (fValue >= 0.0 ? 1.0 : -1.0 );
2028 }
2029 
2030 /* Calculates a QR decomposition with Householder reflection.
2031  * For each NxK matrix A exists a decomposition A=Q*R with an orthogonal
2032  * NxN matrix Q and a NxK matrix R.
2033  * Q=H1*H2*...*Hk with Householder matrices H. Such a householder matrix can
2034  * be build from a vector u by H=I-(2/u'u)*(u u'). This vectors u are returned
2035  * in the columns of matrix A, overwriting the old content.
2036  * The matrix R has a quadric upper part KxK with values in the upper right
2037  * triangle and zeros in all other elements. Here the diagonal elements of R
2038  * are stored in the vector R and the other upper right elements in the upper
2039  * right of the matrix A.
2040  * The function returns false, if calculation breaks. But because of round-off
2041  * errors singularity is often not detected.
2042  */
2043 bool lcl_CalculateQRdecomposition(const ScMatrixRef& pMatA,
2044  ::std::vector< double>& pVecR, SCSIZE nK, SCSIZE nN)
2045 {
2046  // ScMatrix matrices are zero based, index access (column,row)
2047  for (SCSIZE col = 0; col <nK; col++)
2048  {
2049  // calculate vector u of the householder transformation
2050  const double fScale = lcl_GetColumnMaximumNorm(pMatA, col, col, nN);
2051  if (fScale == 0.0)
2052  {
2053  // A is singular
2054  return false;
2055  }
2056  for (SCSIZE row = col; row <nN; row++)
2057  pMatA->PutDouble( pMatA->GetDouble(col,row)/fScale, col, row);
2058 
2059  const double fEuclid = lcl_GetColumnEuclideanNorm(pMatA, col, col, nN);
2060  const double fFactor = 1.0/fEuclid/(fEuclid + fabs(pMatA->GetDouble(col,col)));
2061  const double fSignum = lcl_GetSign(pMatA->GetDouble(col,col));
2062  pMatA->PutDouble( pMatA->GetDouble(col,col) + fSignum*fEuclid, col,col);
2063  pVecR[col] = -fSignum * fScale * fEuclid;
2064 
2065  // apply Householder transformation to A
2066  for (SCSIZE c=col+1; c<nK; c++)
2067  {
2068  const double fSum =lcl_GetColumnSumProduct(pMatA, col, pMatA, c, col, nN);
2069  for (SCSIZE row = col; row <nN; row++)
2070  pMatA->PutDouble( pMatA->GetDouble(c,row) - fSum * fFactor * pMatA->GetDouble(col,row), c, row);
2071  }
2072  }
2073  return true;
2074 }
2075 
2076 // same with transposed matrix A, N is count of columns, K count of rows
2077 bool lcl_TCalculateQRdecomposition(const ScMatrixRef& pMatA,
2078  ::std::vector< double>& pVecR, SCSIZE nK, SCSIZE nN)
2079 {
2080  double fSum ;
2081  // ScMatrix matrices are zero based, index access (column,row)
2082  for (SCSIZE row = 0; row <nK; row++)
2083  {
2084  // calculate vector u of the householder transformation
2085  const double fScale = lcl_TGetColumnMaximumNorm(pMatA, row, row, nN);
2086  if (fScale == 0.0)
2087  {
2088  // A is singular
2089  return false;
2090  }
2091  for (SCSIZE col = row; col <nN; col++)
2092  pMatA->PutDouble( pMatA->GetDouble(col,row)/fScale, col, row);
2093 
2094  const double fEuclid = lcl_TGetColumnEuclideanNorm(pMatA, row, row, nN);
2095  const double fFactor = 1.0/fEuclid/(fEuclid + fabs(pMatA->GetDouble(row,row)));
2096  const double fSignum = lcl_GetSign(pMatA->GetDouble(row,row));
2097  pMatA->PutDouble( pMatA->GetDouble(row,row) + fSignum*fEuclid, row,row);
2098  pVecR[row] = -fSignum * fScale * fEuclid;
2099 
2100  // apply Householder transformation to A
2101  for (SCSIZE r=row+1; r<nK; r++)
2102  {
2103  fSum =lcl_TGetColumnSumProduct(pMatA, row, pMatA, r, row, nN);
2104  for (SCSIZE col = row; col <nN; col++)
2105  pMatA->PutDouble(
2106  pMatA->GetDouble(col,r) - fSum * fFactor * pMatA->GetDouble(col,row), col, r);
2107  }
2108  }
2109  return true;
2110 }
2111 
2112 /* Applies a Householder transformation to a column vector Y with is given as
2113  * Nx1 Matrix. The vector u, from which the Householder transformation is built,
2114  * is the column part in matrix A, with column index C, starting with row
2115  * index C. A is the result of the QR decomposition as obtained from
2116  * lcl_CalculateQRdecomposition.
2117  */
2118 void lcl_ApplyHouseholderTransformation(const ScMatrixRef& pMatA, SCSIZE nC,
2119  const ScMatrixRef& pMatY, SCSIZE nN)
2120 {
2121  // ScMatrix matrices are zero based, index access (column,row)
2122  double fDenominator = lcl_GetColumnSumProduct(pMatA, nC, pMatA, nC, nC, nN);
2123  double fNumerator = lcl_GetColumnSumProduct(pMatA, nC, pMatY, 0, nC, nN);
2124  double fFactor = 2.0 * (fNumerator/fDenominator);
2125  for (SCSIZE row = nC; row < nN; row++)
2126  pMatY->PutDouble(
2127  pMatY->GetDouble(row) - fFactor * pMatA->GetDouble(nC,row), row);
2128 }
2129 
2130 // Same with transposed matrices A and Y.
2131 void lcl_TApplyHouseholderTransformation(const ScMatrixRef& pMatA, SCSIZE nR,
2132  const ScMatrixRef& pMatY, SCSIZE nN)
2133 {
2134  // ScMatrix matrices are zero based, index access (column,row)
2135  double fDenominator = lcl_TGetColumnSumProduct(pMatA, nR, pMatA, nR, nR, nN);
2136  double fNumerator = lcl_TGetColumnSumProduct(pMatA, nR, pMatY, 0, nR, nN);
2137  double fFactor = 2.0 * (fNumerator/fDenominator);
2138  for (SCSIZE col = nR; col < nN; col++)
2139  pMatY->PutDouble(
2140  pMatY->GetDouble(col) - fFactor * pMatA->GetDouble(col,nR), col);
2141 }
2142 
2143 /* Solve for X in R*X=S using back substitution. The solution X overwrites S.
2144  * Uses R from the result of the QR decomposition of a NxK matrix A.
2145  * S is a column vector given as matrix, with at least elements on index
2146  * 0 to K-1; elements on index>=K are ignored. Vector R must not have zero
2147  * elements, no check is done.
2148  */
2149 void lcl_SolveWithUpperRightTriangle(const ScMatrixRef& pMatA,
2150  ::std::vector< double>& pVecR, const ScMatrixRef& pMatS,
2151  SCSIZE nK, bool bIsTransposed)
2152 {
2153  // ScMatrix matrices are zero based, index access (column,row)
2154  SCSIZE row;
2155  // SCSIZE is never negative, therefore test with rowp1=row+1
2156  for (SCSIZE rowp1 = nK; rowp1>0; rowp1--)
2157  {
2158  row = rowp1-1;
2159  double fSum = pMatS->GetDouble(row);
2160  for (SCSIZE col = rowp1; col<nK ; col++)
2161  if (bIsTransposed)
2162  fSum -= pMatA->GetDouble(row,col) * pMatS->GetDouble(col);
2163  else
2164  fSum -= pMatA->GetDouble(col,row) * pMatS->GetDouble(col);
2165  pMatS->PutDouble( fSum / pVecR[row] , row);
2166  }
2167 }
2168 
2169 /* Solve for X in R' * X= T using forward substitution. The solution X
2170  * overwrites T. Uses R from the result of the QR decomposition of a NxK
2171  * matrix A. T is a column vectors given as matrix, with at least elements on
2172  * index 0 to K-1; elements on index>=K are ignored. Vector R must not have
2173  * zero elements, no check is done.
2174  */
2175 void lcl_SolveWithLowerLeftTriangle(const ScMatrixRef& pMatA,
2176  ::std::vector< double>& pVecR, const ScMatrixRef& pMatT,
2177  SCSIZE nK, bool bIsTransposed)
2178 {
2179  // ScMatrix matrices are zero based, index access (column,row)
2180  for (SCSIZE row = 0; row < nK; row++)
2181  {
2182  double fSum = pMatT -> GetDouble(row);
2183  for (SCSIZE col=0; col < row; col++)
2184  {
2185  if (bIsTransposed)
2186  fSum -= pMatA->GetDouble(col,row) * pMatT->GetDouble(col);
2187  else
2188  fSum -= pMatA->GetDouble(row,col) * pMatT->GetDouble(col);
2189  }
2190  pMatT->PutDouble( fSum / pVecR[row] , row);
2191  }
2192 }
2193 
2194 /* Calculates Z = R * B
2195  * R is given in matrix A and vector VecR as obtained from the QR
2196  * decomposition in lcl_CalculateQRdecomposition. B and Z are column vectors
2197  * given as matrix with at least index 0 to K-1; elements on index>=K are
2198  * not used.
2199  */
2200 void lcl_ApplyUpperRightTriangle(const ScMatrixRef& pMatA,
2201  ::std::vector< double>& pVecR, const ScMatrixRef& pMatB,
2202  const ScMatrixRef& pMatZ, SCSIZE nK, bool bIsTransposed)
2203 {
2204  // ScMatrix matrices are zero based, index access (column,row)
2205  for (SCSIZE row = 0; row < nK; row++)
2206  {
2207  double fSum = pVecR[row] * pMatB->GetDouble(row);
2208  for (SCSIZE col = row+1; col < nK; col++)
2209  if (bIsTransposed)
2210  fSum += pMatA->GetDouble(row,col) * pMatB->GetDouble(col);
2211  else
2212  fSum += pMatA->GetDouble(col,row) * pMatB->GetDouble(col);
2213  pMatZ->PutDouble( fSum, row);
2214  }
2215 }
2216 
2217 double lcl_GetMeanOverAll(const ScMatrixRef& pMat, SCSIZE nN)
2218 {
2219  double fSum = 0.0;
2220  for (SCSIZE i=0 ; i<nN; i++)
2221  fSum += pMat->GetDouble(i);
2222  return fSum/static_cast<double>(nN);
2223 }
2224 
2225 // Calculates means of the columns of matrix X. X is a RxC matrix;
2226 // ResMat is a 1xC matrix (=row).
2227 void lcl_CalculateColumnMeans(const ScMatrixRef& pX, const ScMatrixRef& pResMat,
2228  SCSIZE nC, SCSIZE nR)
2229 {
2230  for (SCSIZE i=0; i < nC; i++)
2231  {
2232  double fSum =0.0;
2233  for (SCSIZE k=0; k < nR; k++)
2234  fSum += pX->GetDouble(i,k); // GetDouble(Column,Row)
2235  pResMat ->PutDouble( fSum/static_cast<double>(nR),i);
2236  }
2237 }
2238 
2239 // Calculates means of the rows of matrix X. X is a RxC matrix;
2240 // ResMat is a Rx1 matrix (=column).
2241 void lcl_CalculateRowMeans(const ScMatrixRef& pX, const ScMatrixRef& pResMat,
2242  SCSIZE nC, SCSIZE nR)
2243 {
2244  for (SCSIZE k=0; k < nR; k++)
2245  {
2246  double fSum = 0.0;
2247  for (SCSIZE i=0; i < nC; i++)
2248  fSum += pX->GetDouble(i,k); // GetDouble(Column,Row)
2249  pResMat ->PutDouble( fSum/static_cast<double>(nC),k);
2250  }
2251 }
2252 
2253 void lcl_CalculateColumnsDelta(const ScMatrixRef& pMat, const ScMatrixRef& pColumnMeans,
2254  SCSIZE nC, SCSIZE nR)
2255 {
2256  for (SCSIZE i = 0; i < nC; i++)
2257  for (SCSIZE k = 0; k < nR; k++)
2258  pMat->PutDouble( ::rtl::math::approxSub
2259  (pMat->GetDouble(i,k) , pColumnMeans->GetDouble(i) ) , i, k);
2260 }
2261 
2262 void lcl_CalculateRowsDelta(const ScMatrixRef& pMat, const ScMatrixRef& pRowMeans,
2263  SCSIZE nC, SCSIZE nR)
2264 {
2265  for (SCSIZE k = 0; k < nR; k++)
2266  for (SCSIZE i = 0; i < nC; i++)
2267  pMat->PutDouble( ::rtl::math::approxSub
2268  ( pMat->GetDouble(i,k) , pRowMeans->GetDouble(k) ) , i, k);
2269 }
2270 
2271 // Case1 = simple regression
2272 // MatX = X - MeanX, MatY = Y - MeanY, y - haty = (y - MeanY) - (haty - MeanY)
2273 // = (y-MeanY)-((slope*x+a)-(slope*MeanX+a)) = (y-MeanY)-slope*(x-MeanX)
2274 double lcl_GetSSresid(const ScMatrixRef& pMatX, const ScMatrixRef& pMatY, double fSlope,
2275  SCSIZE nN)
2276 {
2277  double fSum = 0.0;
2278  for (SCSIZE i=0; i<nN; i++)
2279  {
2280  const double fTemp = pMatY->GetDouble(i) - fSlope * pMatX->GetDouble(i);
2281  fSum += fTemp * fTemp;
2282  }
2283  return fSum;
2284 }
2285 
2286 }
2287 
2288 // Fill default values in matrix X, transform Y to log(Y) in case LOGEST|GROWTH,
2289 // determine sizes of matrices X and Y, determine kind of regression, clone
2290 // Y in case LOGEST|GROWTH, if constant.
2291 bool ScInterpreter::CheckMatrix(bool _bLOG, sal_uInt8& nCase, SCSIZE& nCX,
2292  SCSIZE& nCY, SCSIZE& nRX, SCSIZE& nRY, SCSIZE& M,
2293  SCSIZE& N, ScMatrixRef& pMatX, ScMatrixRef& pMatY)
2294 {
2295 
2296  nCX = 0;
2297  nCY = 0;
2298  nRX = 0;
2299  nRY = 0;
2300  M = 0;
2301  N = 0;
2302  pMatY->GetDimensions(nCY, nRY);
2303  const SCSIZE nCountY = nCY * nRY;
2304  for ( SCSIZE i = 0; i < nCountY; i++ )
2305  {
2306  if (!pMatY->IsValue(i))
2307  {
2308  PushIllegalArgument();
2309  return false;
2310  }
2311  }
2312 
2313  if ( _bLOG )
2314  {
2315  ScMatrixRef pNewY = pMatY->CloneIfConst();
2316  for (SCSIZE nElem = 0; nElem < nCountY; nElem++)
2317  {
2318  const double fVal = pNewY->GetDouble(nElem);
2319  if (fVal <= 0.0)
2320  {
2321  PushIllegalArgument();
2322  return false;
2323  }
2324  else
2325  pNewY->PutDouble(log(fVal), nElem);
2326  }
2327  pMatY = pNewY;
2328  }
2329 
2330  if (pMatX)
2331  {
2332  pMatX->GetDimensions(nCX, nRX);
2333  const SCSIZE nCountX = nCX * nRX;
2334  for ( SCSIZE i = 0; i < nCountX; i++ )
2335  if (!pMatX->IsValue(i))
2336  {
2337  PushIllegalArgument();
2338  return false;
2339  }
2340  if (nCX == nCY && nRX == nRY)
2341  {
2342  nCase = 1; // simple regression
2343  M = 1;
2344  N = nCountY;
2345  }
2346  else if (nCY != 1 && nRY != 1)
2347  {
2348  PushIllegalArgument();
2349  return false;
2350  }
2351  else if (nCY == 1)
2352  {
2353  if (nRX != nRY)
2354  {
2355  PushIllegalArgument();
2356  return false;
2357  }
2358  else
2359  {
2360  nCase = 2; // Y is column
2361  N = nRY;
2362  M = nCX;
2363  }
2364  }
2365  else if (nCX != nCY)
2366  {
2367  PushIllegalArgument();
2368  return false;
2369  }
2370  else
2371  {
2372  nCase = 3; // Y is row
2373  N = nCY;
2374  M = nRX;
2375  }
2376  }
2377  else
2378  {
2379  pMatX = GetNewMat(nCY, nRY);
2380  nCX = nCY;
2381  nRX = nRY;
2382  if (!pMatX)
2383  {
2384  PushIllegalArgument();
2385  return false;
2386  }
2387  for ( SCSIZE i = 1; i <= nCountY; i++ )
2388  pMatX->PutDouble(static_cast<double>(i), i-1);
2389  nCase = 1;
2390  N = nCountY;
2391  M = 1;
2392  }
2393  return true;
2394 }
2395 
2396 // LINEST
2398 {
2399  CalculateRGPRKP(false);
2400 }
2401 
2402 // LOGEST
2404 {
2405  CalculateRGPRKP(true);
2406 }
2407 
2409 {
2410  sal_uInt8 nParamCount = GetByte();
2411  if (!MustHaveParamCount( nParamCount, 1, 4 ))
2412  return;
2413  bool bConstant, bStats;
2414 
2415  // optional forth parameter
2416  if (nParamCount == 4)
2417  bStats = GetBool();
2418  else
2419  bStats = false;
2420 
2421  // The third parameter may not be missing in ODF, if the forth parameter
2422  // is present. But Excel allows it with default true, we too.
2423  if (nParamCount >= 3)
2424  {
2425  if (IsMissing())
2426  {
2427  Pop();
2428  bConstant = true;
2429 // PushIllegalParameter(); if ODF behavior is desired
2430 // return;
2431  }
2432  else
2433  bConstant = GetBool();
2434  }
2435  else
2436  bConstant = true;
2437 
2438  ScMatrixRef pMatX;
2439  if (nParamCount >= 2)
2440  {
2441  if (IsMissing())
2442  { //In ODF1.2 empty second parameter (which is two ;; ) is allowed
2443  Pop();
2444  pMatX = nullptr;
2445  }
2446  else
2447  {
2448  pMatX = GetMatrix();
2449  }
2450  }
2451  else
2452  pMatX = nullptr;
2453 
2454  ScMatrixRef pMatY = GetMatrix();
2455  if (!pMatY)
2456  {
2457  PushIllegalParameter();
2458  return;
2459  }
2460 
2461  // 1 = simple; 2 = multiple with Y as column; 3 = multiple with Y as row
2462  sal_uInt8 nCase;
2463 
2464  SCSIZE nCX, nCY; // number of columns
2465  SCSIZE nRX, nRY; //number of rows
2466  SCSIZE K = 0, N = 0; // K=number of variables X, N=number of data samples
2467  if (!CheckMatrix(_bRKP,nCase,nCX,nCY,nRX,nRY,K,N,pMatX,pMatY))
2468  {
2469  PushIllegalParameter();
2470  return;
2471  }
2472 
2473  // Enough data samples?
2474  if ((bConstant && (N<K+1)) || (!bConstant && (N<K)) || (N<1) || (K<1))
2475  {
2476  PushIllegalParameter();
2477  return;
2478  }
2479 
2480  ScMatrixRef pResMat;
2481  if (bStats)
2482  pResMat = GetNewMat(K+1,5);
2483  else
2484  pResMat = GetNewMat(K+1,1);
2485  if (!pResMat)
2486  {
2487  PushError(FormulaError::CodeOverflow);
2488  return;
2489  }
2490  // Fill unused cells in pResMat; order (column,row)
2491  if (bStats)
2492  {
2493  for (SCSIZE i=2; i<K+1; i++)
2494  {
2495  pResMat->PutError( FormulaError::NotAvailable, i, 2);
2496  pResMat->PutError( FormulaError::NotAvailable, i, 3);
2497  pResMat->PutError( FormulaError::NotAvailable, i, 4);
2498  }
2499  }
2500 
2501  // Uses sum(x-MeanX)^2 and not [sum x^2]-N * MeanX^2 in case bConstant.
2502  // Clone constant matrices, so that Mat = Mat - Mean is possible.
2503  double fMeanY = 0.0;
2504  if (bConstant)
2505  {
2506  ScMatrixRef pNewX = pMatX->CloneIfConst();
2507  ScMatrixRef pNewY = pMatY->CloneIfConst();
2508  if (!pNewX || !pNewY)
2509  {
2510  PushError(FormulaError::CodeOverflow);
2511  return;
2512  }
2513  pMatX = pNewX;
2514  pMatY = pNewY;
2515  // DeltaY is possible here; DeltaX depends on nCase, so later
2516  fMeanY = lcl_GetMeanOverAll(pMatY, N);
2517  for (SCSIZE i=0; i<N; i++)
2518  {
2519  pMatY->PutDouble( ::rtl::math::approxSub(pMatY->GetDouble(i),fMeanY), i );
2520  }
2521  }
2522 
2523  if (nCase==1)
2524  {
2525  // calculate simple regression
2526  double fMeanX = 0.0;
2527  if (bConstant)
2528  { // Mat = Mat - Mean
2529  fMeanX = lcl_GetMeanOverAll(pMatX, N);
2530  for (SCSIZE i=0; i<N; i++)
2531  {
2532  pMatX->PutDouble( ::rtl::math::approxSub(pMatX->GetDouble(i),fMeanX), i );
2533  }
2534  }
2535  double fSumXY = lcl_GetSumProduct(pMatX,pMatY,N);
2536  double fSumX2 = lcl_GetSumProduct(pMatX,pMatX,N);
2537  if (fSumX2==0.0)
2538  {
2539  PushNoValue(); // all x-values are identical
2540  return;
2541  }
2542  double fSlope = fSumXY / fSumX2;
2543  double fIntercept = 0.0;
2544  if (bConstant)
2545  fIntercept = fMeanY - fSlope * fMeanX;
2546  pResMat->PutDouble(_bRKP ? exp(fIntercept) : fIntercept, 1, 0); //order (column,row)
2547  pResMat->PutDouble(_bRKP ? exp(fSlope) : fSlope, 0, 0);
2548 
2549  if (bStats)
2550  {
2551  double fSSreg = fSlope * fSlope * fSumX2;
2552  pResMat->PutDouble(fSSreg, 0, 4);
2553 
2554  double fDegreesFreedom =static_cast<double>( bConstant ? N-2 : N-1 );
2555  pResMat->PutDouble(fDegreesFreedom, 1, 3);
2556 
2557  double fSSresid = lcl_GetSSresid(pMatX,pMatY,fSlope,N);
2558  pResMat->PutDouble(fSSresid, 1, 4);
2559 
2560  if (fDegreesFreedom == 0.0 || fSSresid == 0.0 || fSSreg == 0.0)
2561  { // exact fit; test SSreg too, because SSresid might be
2562  // unequal zero due to round of errors
2563  pResMat->PutDouble(0.0, 1, 4); // SSresid
2564  pResMat->PutError( FormulaError::NotAvailable, 0, 3); // F
2565  pResMat->PutDouble(0.0, 1, 2); // RMSE
2566  pResMat->PutDouble(0.0, 0, 1); // SigmaSlope
2567  if (bConstant)
2568  pResMat->PutDouble(0.0, 1, 1); //SigmaIntercept
2569  else
2570  pResMat->PutError( FormulaError::NotAvailable, 1, 1);
2571  pResMat->PutDouble(1.0, 0, 2); // R^2
2572  }
2573  else
2574  {
2575  double fFstatistic = (fSSreg / static_cast<double>(K))
2576  / (fSSresid / fDegreesFreedom);
2577  pResMat->PutDouble(fFstatistic, 0, 3);
2578 
2579  // standard error of estimate
2580  double fRMSE = sqrt(fSSresid / fDegreesFreedom);
2581  pResMat->PutDouble(fRMSE, 1, 2);
2582 
2583  double fSigmaSlope = fRMSE / sqrt(fSumX2);
2584  pResMat->PutDouble(fSigmaSlope, 0, 1);
2585 
2586  if (bConstant)
2587  {
2588  double fSigmaIntercept = fRMSE
2589  * sqrt(fMeanX*fMeanX/fSumX2 + 1.0/static_cast<double>(N));
2590  pResMat->PutDouble(fSigmaIntercept, 1, 1);
2591  }
2592  else
2593  {
2594  pResMat->PutError( FormulaError::NotAvailable, 1, 1);
2595  }
2596 
2597  double fR2 = fSSreg / (fSSreg + fSSresid);
2598  pResMat->PutDouble(fR2, 0, 2);
2599  }
2600  }
2601  PushMatrix(pResMat);
2602  }
2603  else // calculate multiple regression;
2604  {
2605  // Uses a QR decomposition X = QR. The solution B = (X'X)^(-1) * X' * Y
2606  // becomes B = R^(-1) * Q' * Y
2607  if (nCase ==2) // Y is column
2608  {
2609  ::std::vector< double> aVecR(N); // for QR decomposition
2610  // Enough memory for needed matrices?
2611  ScMatrixRef pMeans = GetNewMat(K, 1); // mean of each column
2612  ScMatrixRef pMatZ; // for Q' * Y , inter alia
2613  if (bStats)
2614  pMatZ = pMatY->Clone(); // Y is used in statistic, keep it
2615  else
2616  pMatZ = pMatY; // Y can be overwritten
2617  ScMatrixRef pSlopes = GetNewMat(1,K); // from b1 to bK
2618  if (!pMeans || !pMatZ || !pSlopes)
2619  {
2620  PushError(FormulaError::CodeOverflow);
2621  return;
2622  }
2623  if (bConstant)
2624  {
2625  lcl_CalculateColumnMeans(pMatX, pMeans, K, N);
2626  lcl_CalculateColumnsDelta(pMatX, pMeans, K, N);
2627  }
2628  if (!lcl_CalculateQRdecomposition(pMatX, aVecR, K, N))
2629  {
2630  PushNoValue();
2631  return;
2632  }
2633  // Later on we will divide by elements of aVecR, so make sure
2634  // that they aren't zero.
2635  bool bIsSingular=false;
2636  for (SCSIZE row=0; row < K && !bIsSingular; row++)
2637  bIsSingular = aVecR[row] == 0.0;
2638  if (bIsSingular)
2639  {
2640  PushNoValue();
2641  return;
2642  }
2643  // Z = Q' Y;
2644  for (SCSIZE col = 0; col < K; col++)
2645  {
2646  lcl_ApplyHouseholderTransformation(pMatX, col, pMatZ, N);
2647  }
2648  // B = R^(-1) * Q' * Y <=> B = R^(-1) * Z <=> R * B = Z
2649  // result Z should have zeros for index>=K; if not, ignore values
2650  for (SCSIZE col = 0; col < K ; col++)
2651  {
2652  pSlopes->PutDouble( pMatZ->GetDouble(col), col);
2653  }
2654  lcl_SolveWithUpperRightTriangle(pMatX, aVecR, pSlopes, K, false);
2655  double fIntercept = 0.0;
2656  if (bConstant)
2657  fIntercept = fMeanY - lcl_GetSumProduct(pMeans,pSlopes,K);
2658  // Fill first line in result matrix
2659  pResMat->PutDouble(_bRKP ? exp(fIntercept) : fIntercept, K, 0 );
2660  for (SCSIZE i = 0; i < K; i++)
2661  pResMat->PutDouble(_bRKP ? exp(pSlopes->GetDouble(i))
2662  : pSlopes->GetDouble(i) , K-1-i, 0);
2663 
2664  if (bStats)
2665  {
2666  double fSSreg = 0.0;
2667  double fSSresid = 0.0;
2668  // re-use memory of Z;
2669  pMatZ->FillDouble(0.0, 0, 0, 0, N-1);
2670  // Z = R * Slopes
2671  lcl_ApplyUpperRightTriangle(pMatX, aVecR, pSlopes, pMatZ, K, false);
2672  // Z = Q * Z, that is Q * R * Slopes = X * Slopes
2673  for (SCSIZE colp1 = K; colp1 > 0; colp1--)
2674  {
2675  lcl_ApplyHouseholderTransformation(pMatX, colp1-1, pMatZ,N);
2676  }
2677  fSSreg =lcl_GetSumProduct(pMatZ, pMatZ, N);
2678  // re-use Y for residuals, Y = Y-Z
2679  for (SCSIZE row = 0; row < N; row++)
2680  pMatY->PutDouble(pMatY->GetDouble(row) - pMatZ->GetDouble(row), row);
2681  fSSresid = lcl_GetSumProduct(pMatY, pMatY, N);
2682  pResMat->PutDouble(fSSreg, 0, 4);
2683  pResMat->PutDouble(fSSresid, 1, 4);
2684 
2685  double fDegreesFreedom =static_cast<double>( bConstant ? N-K-1 : N-K );
2686  pResMat->PutDouble(fDegreesFreedom, 1, 3);
2687 
2688  if (fDegreesFreedom == 0.0 || fSSresid == 0.0 || fSSreg == 0.0)
2689  { // exact fit; incl. observed values Y are identical
2690  pResMat->PutDouble(0.0, 1, 4); // SSresid
2691  // F = (SSreg/K) / (SSresid/df) = #DIV/0!
2692  pResMat->PutError( FormulaError::NotAvailable, 0, 3); // F
2693  // RMSE = sqrt(SSresid / df) = sqrt(0 / df) = 0
2694  pResMat->PutDouble(0.0, 1, 2); // RMSE
2695  // SigmaSlope[i] = RMSE * sqrt(matrix[i,i]) = 0 * sqrt(...) = 0
2696  for (SCSIZE i=0; i<K; i++)
2697  pResMat->PutDouble(0.0, K-1-i, 1);
2698 
2699  // SigmaIntercept = RMSE * sqrt(...) = 0
2700  if (bConstant)
2701  pResMat->PutDouble(0.0, K, 1); //SigmaIntercept
2702  else
2703  pResMat->PutError( FormulaError::NotAvailable, K, 1);
2704 
2705  // R^2 = SSreg / (SSreg + SSresid) = 1.0
2706  pResMat->PutDouble(1.0, 0, 2); // R^2
2707  }
2708  else
2709  {
2710  double fFstatistic = (fSSreg / static_cast<double>(K))
2711  / (fSSresid / fDegreesFreedom);
2712  pResMat->PutDouble(fFstatistic, 0, 3);
2713 
2714  // standard error of estimate = root mean SSE
2715  double fRMSE = sqrt(fSSresid / fDegreesFreedom);
2716  pResMat->PutDouble(fRMSE, 1, 2);
2717 
2718  // standard error of slopes
2719  // = RMSE * sqrt(diagonal element of (R' R)^(-1) )
2720  // standard error of intercept
2721  // = RMSE * sqrt( Xmean * (R' R)^(-1) * Xmean' + 1/N)
2722  // (R' R)^(-1) = R^(-1) * (R')^(-1). Do not calculate it as
2723  // a whole matrix, but iterate over unit vectors.
2724  double fSigmaIntercept = 0.0;
2725  double fPart; // for Xmean * single column of (R' R)^(-1)
2726  for (SCSIZE col = 0; col < K; col++)
2727  {
2728  //re-use memory of MatZ
2729  pMatZ->FillDouble(0.0,0,0,0,K-1); // Z = unit vector e
2730  pMatZ->PutDouble(1.0, col);
2731  //Solve R' * Z = e
2732  lcl_SolveWithLowerLeftTriangle(pMatX, aVecR, pMatZ, K, false);
2733  // Solve R * Znew = Zold
2734  lcl_SolveWithUpperRightTriangle(pMatX, aVecR, pMatZ, K, false);
2735  // now Z is column col in (R' R)^(-1)
2736  double fSigmaSlope = fRMSE * sqrt(pMatZ->GetDouble(col));
2737  pResMat->PutDouble(fSigmaSlope, K-1-col, 1);
2738  // (R' R) ^(-1) is symmetric
2739  if (bConstant)
2740  {
2741  fPart = lcl_GetSumProduct(pMeans, pMatZ, K);
2742  fSigmaIntercept += fPart * pMeans->GetDouble(col);
2743  }
2744  }
2745  if (bConstant)
2746  {
2747  fSigmaIntercept = fRMSE
2748  * sqrt(fSigmaIntercept + 1.0 / static_cast<double>(N));
2749  pResMat->PutDouble(fSigmaIntercept, K, 1);
2750  }
2751  else
2752  {
2753  pResMat->PutError( FormulaError::NotAvailable, K, 1);
2754  }
2755 
2756  double fR2 = fSSreg / (fSSreg + fSSresid);
2757  pResMat->PutDouble(fR2, 0, 2);
2758  }
2759  }
2760  PushMatrix(pResMat);
2761  }
2762  else // nCase == 3, Y is row, all matrices are transposed
2763  {
2764  ::std::vector< double> aVecR(N); // for QR decomposition
2765  // Enough memory for needed matrices?
2766  ScMatrixRef pMeans = GetNewMat(1, K); // mean of each row
2767  ScMatrixRef pMatZ; // for Q' * Y , inter alia
2768  if (bStats)
2769  pMatZ = pMatY->Clone(); // Y is used in statistic, keep it
2770  else
2771  pMatZ = pMatY; // Y can be overwritten
2772  ScMatrixRef pSlopes = GetNewMat(K,1); // from b1 to bK
2773  if (!pMeans || !pMatZ || !pSlopes)
2774  {
2775  PushError(FormulaError::CodeOverflow);
2776  return;
2777  }
2778  if (bConstant)
2779  {
2780  lcl_CalculateRowMeans(pMatX, pMeans, N, K);
2781  lcl_CalculateRowsDelta(pMatX, pMeans, N, K);
2782  }
2783 
2784  if (!lcl_TCalculateQRdecomposition(pMatX, aVecR, K, N))
2785  {
2786  PushNoValue();
2787  return;
2788  }
2789 
2790  // Later on we will divide by elements of aVecR, so make sure
2791  // that they aren't zero.
2792  bool bIsSingular=false;
2793  for (SCSIZE row=0; row < K && !bIsSingular; row++)
2794  bIsSingular = aVecR[row] == 0.0;
2795  if (bIsSingular)
2796  {
2797  PushNoValue();
2798  return;
2799  }
2800  // Z = Q' Y
2801  for (SCSIZE row = 0; row < K; row++)
2802  {
2803  lcl_TApplyHouseholderTransformation(pMatX, row, pMatZ, N);
2804  }
2805  // B = R^(-1) * Q' * Y <=> B = R^(-1) * Z <=> R * B = Z
2806  // result Z should have zeros for index>=K; if not, ignore values
2807  for (SCSIZE col = 0; col < K ; col++)
2808  {
2809  pSlopes->PutDouble( pMatZ->GetDouble(col), col);
2810  }
2811  lcl_SolveWithUpperRightTriangle(pMatX, aVecR, pSlopes, K, true);
2812  double fIntercept = 0.0;
2813  if (bConstant)
2814  fIntercept = fMeanY - lcl_GetSumProduct(pMeans,pSlopes,K);
2815  // Fill first line in result matrix
2816  pResMat->PutDouble(_bRKP ? exp(fIntercept) : fIntercept, K, 0 );
2817  for (SCSIZE i = 0; i < K; i++)
2818  pResMat->PutDouble(_bRKP ? exp(pSlopes->GetDouble(i))
2819  : pSlopes->GetDouble(i) , K-1-i, 0);
2820 
2821  if (bStats)
2822  {
2823  double fSSreg = 0.0;
2824  double fSSresid = 0.0;
2825  // re-use memory of Z;
2826  pMatZ->FillDouble(0.0, 0, 0, N-1, 0);
2827  // Z = R * Slopes
2828  lcl_ApplyUpperRightTriangle(pMatX, aVecR, pSlopes, pMatZ, K, true);
2829  // Z = Q * Z, that is Q * R * Slopes = X * Slopes
2830  for (SCSIZE rowp1 = K; rowp1 > 0; rowp1--)
2831  {
2832  lcl_TApplyHouseholderTransformation(pMatX, rowp1-1, pMatZ,N);
2833  }
2834  fSSreg =lcl_GetSumProduct(pMatZ, pMatZ, N);
2835  // re-use Y for residuals, Y = Y-Z
2836  for (SCSIZE col = 0; col < N; col++)
2837  pMatY->PutDouble(pMatY->GetDouble(col) - pMatZ->GetDouble(col), col);
2838  fSSresid = lcl_GetSumProduct(pMatY, pMatY, N);
2839  pResMat->PutDouble(fSSreg, 0, 4);
2840  pResMat->PutDouble(fSSresid, 1, 4);
2841 
2842  double fDegreesFreedom =static_cast<double>( bConstant ? N-K-1 : N-K );
2843  pResMat->PutDouble(fDegreesFreedom, 1, 3);
2844 
2845  if (fDegreesFreedom == 0.0 || fSSresid == 0.0 || fSSreg == 0.0)
2846  { // exact fit; incl. case observed values Y are identical
2847  pResMat->PutDouble(0.0, 1, 4); // SSresid
2848  // F = (SSreg/K) / (SSresid/df) = #DIV/0!
2849  pResMat->PutError( FormulaError::NotAvailable, 0, 3); // F
2850  // RMSE = sqrt(SSresid / df) = sqrt(0 / df) = 0
2851  pResMat->PutDouble(0.0, 1, 2); // RMSE
2852  // SigmaSlope[i] = RMSE * sqrt(matrix[i,i]) = 0 * sqrt(...) = 0
2853  for (SCSIZE i=0; i<K; i++)
2854  pResMat->PutDouble(0.0, K-1-i, 1);
2855 
2856  // SigmaIntercept = RMSE * sqrt(...) = 0
2857  if (bConstant)
2858  pResMat->PutDouble(0.0, K, 1); //SigmaIntercept
2859  else
2860  pResMat->PutError( FormulaError::NotAvailable, K, 1);
2861 
2862  // R^2 = SSreg / (SSreg + SSresid) = 1.0
2863  pResMat->PutDouble(1.0, 0, 2); // R^2
2864  }
2865  else
2866  {
2867  double fFstatistic = (fSSreg / static_cast<double>(K))
2868  / (fSSresid / fDegreesFreedom);
2869  pResMat->PutDouble(fFstatistic, 0, 3);
2870 
2871  // standard error of estimate = root mean SSE
2872  double fRMSE = sqrt(fSSresid / fDegreesFreedom);
2873  pResMat->PutDouble(fRMSE, 1, 2);
2874 
2875  // standard error of slopes
2876  // = RMSE * sqrt(diagonal element of (R' R)^(-1) )
2877  // standard error of intercept
2878  // = RMSE * sqrt( Xmean * (R' R)^(-1) * Xmean' + 1/N)
2879  // (R' R)^(-1) = R^(-1) * (R')^(-1). Do not calculate it as
2880  // a whole matrix, but iterate over unit vectors.
2881  // (R' R) ^(-1) is symmetric
2882  double fSigmaIntercept = 0.0;
2883  double fPart; // for Xmean * single col of (R' R)^(-1)
2884  for (SCSIZE row = 0; row < K; row++)
2885  {
2886  //re-use memory of MatZ
2887  pMatZ->FillDouble(0.0,0,0,K-1,0); // Z = unit vector e
2888  pMatZ->PutDouble(1.0, row);
2889  //Solve R' * Z = e
2890  lcl_SolveWithLowerLeftTriangle(pMatX, aVecR, pMatZ, K, true);
2891  // Solve R * Znew = Zold
2892  lcl_SolveWithUpperRightTriangle(pMatX, aVecR, pMatZ, K, true);
2893  // now Z is column col in (R' R)^(-1)
2894  double fSigmaSlope = fRMSE * sqrt(pMatZ->GetDouble(row));
2895  pResMat->PutDouble(fSigmaSlope, K-1-row, 1);
2896  if (bConstant)
2897  {
2898  fPart = lcl_GetSumProduct(pMeans, pMatZ, K);
2899  fSigmaIntercept += fPart * pMeans->GetDouble(row);
2900  }
2901  }
2902  if (bConstant)
2903  {
2904  fSigmaIntercept = fRMSE
2905  * sqrt(fSigmaIntercept + 1.0 / static_cast<double>(N));
2906  pResMat->PutDouble(fSigmaIntercept, K, 1);
2907  }
2908  else
2909  {
2910  pResMat->PutError( FormulaError::NotAvailable, K, 1);
2911  }
2912 
2913  double fR2 = fSSreg / (fSSreg + fSSresid);
2914  pResMat->PutDouble(fR2, 0, 2);
2915  }
2916  }
2917  PushMatrix(pResMat);
2918  }
2919  }
2920 }
2921 
2923 {
2924  CalculateTrendGrowth(false);
2925 }
2926 
2928 {
2929  CalculateTrendGrowth(true);
2930 }
2931 
2933 {
2934  sal_uInt8 nParamCount = GetByte();
2935  if (!MustHaveParamCount( nParamCount, 1, 4 ))
2936  return;
2937 
2938  // optional forth parameter
2939  bool bConstant;
2940  if (nParamCount == 4)
2941  bConstant = GetBool();
2942  else
2943  bConstant = true;
2944 
2945  // The third parameter may be missing in ODF, although the forth parameter
2946  // is present. Default values depend on data not yet read.
2947  ScMatrixRef pMatNewX;
2948  if (nParamCount >= 3)
2949  {
2950  if (IsMissing())
2951  {
2952  Pop();
2953  pMatNewX = nullptr;
2954  }
2955  else
2956  pMatNewX = GetMatrix();
2957  }
2958  else
2959  pMatNewX = nullptr;
2960 
2961  //In ODF1.2 empty second parameter (which is two ;; ) is allowed
2962  //Defaults will be set in CheckMatrix
2963  ScMatrixRef pMatX;
2964  if (nParamCount >= 2)
2965  {
2966  if (IsMissing())
2967  {
2968  Pop();
2969  pMatX = nullptr;
2970  }
2971  else
2972  {
2973  pMatX = GetMatrix();
2974  }
2975  }
2976  else
2977  pMatX = nullptr;
2978 
2979  ScMatrixRef pMatY = GetMatrix();
2980  if (!pMatY)
2981  {
2982  PushIllegalParameter();
2983  return;
2984  }
2985 
2986  // 1 = simple; 2 = multiple with Y as column; 3 = multiple with Y as row
2987  sal_uInt8 nCase;
2988 
2989  SCSIZE nCX, nCY; // number of columns
2990  SCSIZE nRX, nRY; //number of rows
2991  SCSIZE K = 0, N = 0; // K=number of variables X, N=number of data samples
2992  if (!CheckMatrix(_bGrowth,nCase,nCX,nCY,nRX,nRY,K,N,pMatX,pMatY))
2993  {
2994  PushIllegalParameter();
2995  return;
2996  }
2997 
2998  // Enough data samples?
2999  if ((bConstant && (N<K+1)) || (!bConstant && (N<K)) || (N<1) || (K<1))
3000  {
3001  PushIllegalParameter();
3002  return;
3003  }
3004 
3005  // Set default pMatNewX if necessary
3006  SCSIZE nCXN, nRXN;
3007  SCSIZE nCountXN;
3008  if (!pMatNewX)
3009  {
3010  nCXN = nCX;
3011  nRXN = nRX;
3012  nCountXN = nCXN * nRXN;
3013  pMatNewX = pMatX->Clone(); // pMatX will be changed to X-meanX
3014  }
3015  else
3016  {
3017  pMatNewX->GetDimensions(nCXN, nRXN);
3018  if ((nCase == 2 && K != nCXN) || (nCase == 3 && K != nRXN))
3019  {
3020  PushIllegalArgument();
3021  return;
3022  }
3023  nCountXN = nCXN * nRXN;
3024  for (SCSIZE i = 0; i < nCountXN; i++)
3025  if (!pMatNewX->IsValue(i))
3026  {
3027  PushIllegalArgument();
3028  return;
3029  }
3030  }
3031  ScMatrixRef pResMat; // size depends on nCase
3032  if (nCase == 1)
3033  pResMat = GetNewMat(nCXN,nRXN);
3034  else
3035  {
3036  if (nCase==2)
3037  pResMat = GetNewMat(1,nRXN);
3038  else
3039  pResMat = GetNewMat(nCXN,1);
3040  }
3041  if (!pResMat)
3042  {
3043  PushError(FormulaError::CodeOverflow);
3044  return;
3045  }
3046  // Uses sum(x-MeanX)^2 and not [sum x^2]-N * MeanX^2 in case bConstant.
3047  // Clone constant matrices, so that Mat = Mat - Mean is possible.
3048  double fMeanY = 0.0;
3049  if (bConstant)
3050  {
3051  ScMatrixRef pCopyX = pMatX->CloneIfConst();
3052  ScMatrixRef pCopyY = pMatY->CloneIfConst();
3053  if (!pCopyX || !pCopyY)
3054  {
3055  PushError(FormulaError::MatrixSize);
3056  return;
3057  }
3058  pMatX = pCopyX;
3059  pMatY = pCopyY;
3060  // DeltaY is possible here; DeltaX depends on nCase, so later
3061  fMeanY = lcl_GetMeanOverAll(pMatY, N);
3062  for (SCSIZE i=0; i<N; i++)
3063  {
3064  pMatY->PutDouble( ::rtl::math::approxSub(pMatY->GetDouble(i),fMeanY), i );
3065  }
3066  }
3067 
3068  if (nCase==1)
3069  {
3070  // calculate simple regression
3071  double fMeanX = 0.0;
3072  if (bConstant)
3073  { // Mat = Mat - Mean
3074  fMeanX = lcl_GetMeanOverAll(pMatX, N);
3075  for (SCSIZE i=0; i<N; i++)
3076  {
3077  pMatX->PutDouble( ::rtl::math::approxSub(pMatX->GetDouble(i),fMeanX), i );
3078  }
3079  }
3080  double fSumXY = lcl_GetSumProduct(pMatX,pMatY,N);
3081  double fSumX2 = lcl_GetSumProduct(pMatX,pMatX,N);
3082  if (fSumX2==0.0)
3083  {
3084  PushNoValue(); // all x-values are identical
3085  return;
3086  }
3087  double fSlope = fSumXY / fSumX2;
3088  double fHelp;
3089  if (bConstant)
3090  {
3091  double fIntercept = fMeanY - fSlope * fMeanX;
3092  for (SCSIZE i = 0; i < nCountXN; i++)
3093  {
3094  fHelp = pMatNewX->GetDouble(i)*fSlope + fIntercept;
3095  pResMat->PutDouble(_bGrowth ? exp(fHelp) : fHelp, i);
3096  }
3097  }
3098  else
3099  {
3100  for (SCSIZE i = 0; i < nCountXN; i++)
3101  {
3102  fHelp = pMatNewX->GetDouble(i)*fSlope;
3103  pResMat->PutDouble(_bGrowth ? exp(fHelp) : fHelp, i);
3104  }
3105  }
3106  }
3107  else // calculate multiple regression;
3108  {
3109  if (nCase ==2) // Y is column
3110  {
3111  ::std::vector< double> aVecR(N); // for QR decomposition
3112  // Enough memory for needed matrices?
3113  ScMatrixRef pMeans = GetNewMat(K, 1); // mean of each column
3114  ScMatrixRef pSlopes = GetNewMat(1,K); // from b1 to bK
3115  if (!pMeans || !pSlopes)
3116  {
3117  PushError(FormulaError::CodeOverflow);
3118  return;
3119  }
3120  if (bConstant)
3121  {
3122  lcl_CalculateColumnMeans(pMatX, pMeans, K, N);
3123  lcl_CalculateColumnsDelta(pMatX, pMeans, K, N);
3124  }
3125  if (!lcl_CalculateQRdecomposition(pMatX, aVecR, K, N))
3126  {
3127  PushNoValue();
3128  return;
3129  }
3130  // Later on we will divide by elements of aVecR, so make sure
3131  // that they aren't zero.
3132  bool bIsSingular=false;
3133  for (SCSIZE row=0; row < K && !bIsSingular; row++)
3134  bIsSingular = aVecR[row] == 0.0;
3135  if (bIsSingular)
3136  {
3137  PushNoValue();
3138  return;
3139  }
3140  // Z := Q' Y; Y is overwritten with result Z
3141  for (SCSIZE col = 0; col < K; col++)
3142  {
3143  lcl_ApplyHouseholderTransformation(pMatX, col, pMatY, N);
3144  }
3145  // B = R^(-1) * Q' * Y <=> B = R^(-1) * Z <=> R * B = Z
3146  // result Z should have zeros for index>=K; if not, ignore values
3147  for (SCSIZE col = 0; col < K ; col++)
3148  {
3149  pSlopes->PutDouble( pMatY->GetDouble(col), col);
3150  }
3151  lcl_SolveWithUpperRightTriangle(pMatX, aVecR, pSlopes, K, false);
3152 
3153  // Fill result matrix
3154  lcl_MFastMult(pMatNewX,pSlopes,pResMat,nRXN,K,1);
3155  if (bConstant)
3156  {
3157  double fIntercept = fMeanY - lcl_GetSumProduct(pMeans,pSlopes,K);
3158  for (SCSIZE row = 0; row < nRXN; row++)
3159  pResMat->PutDouble(pResMat->GetDouble(row)+fIntercept, row);
3160  }
3161  if (_bGrowth)
3162  {
3163  for (SCSIZE i = 0; i < nRXN; i++)
3164  pResMat->PutDouble(exp(pResMat->GetDouble(i)), i);
3165  }
3166  }
3167  else
3168  { // nCase == 3, Y is row, all matrices are transposed
3169 
3170  ::std::vector< double> aVecR(N); // for QR decomposition
3171  // Enough memory for needed matrices?
3172  ScMatrixRef pMeans = GetNewMat(1, K); // mean of each row
3173  ScMatrixRef pSlopes = GetNewMat(K,1); // row from b1 to bK
3174  if (!pMeans || !pSlopes)
3175  {
3176  PushError(FormulaError::CodeOverflow);
3177  return;
3178  }
3179  if (bConstant)
3180  {
3181  lcl_CalculateRowMeans(pMatX, pMeans, N, K);
3182  lcl_CalculateRowsDelta(pMatX, pMeans, N, K);
3183  }
3184  if (!lcl_TCalculateQRdecomposition(pMatX, aVecR, K, N))
3185  {
3186  PushNoValue();
3187  return;
3188  }
3189  // Later on we will divide by elements of aVecR, so make sure
3190  // that they aren't zero.
3191  bool bIsSingular=false;
3192  for (SCSIZE row=0; row < K && !bIsSingular; row++)
3193  bIsSingular = aVecR[row] == 0.0;
3194  if (bIsSingular)
3195  {
3196  PushNoValue();
3197  return;
3198  }
3199  // Z := Q' Y; Y is overwritten with result Z
3200  for (SCSIZE row = 0; row < K; row++)
3201  {
3202  lcl_TApplyHouseholderTransformation(pMatX, row, pMatY, N);
3203  }
3204  // B = R^(-1) * Q' * Y <=> B = R^(-1) * Z <=> R * B = Z
3205  // result Z should have zeros for index>=K; if not, ignore values
3206  for (SCSIZE col = 0; col < K ; col++)
3207  {
3208  pSlopes->PutDouble( pMatY->GetDouble(col), col);
3209  }
3210  lcl_SolveWithUpperRightTriangle(pMatX, aVecR, pSlopes, K, true);
3211 
3212  // Fill result matrix
3213  lcl_MFastMult(pSlopes,pMatNewX,pResMat,1,K,nCXN);
3214  if (bConstant)
3215  {
3216  double fIntercept = fMeanY - lcl_GetSumProduct(pMeans,pSlopes,K);
3217  for (SCSIZE col = 0; col < nCXN; col++)
3218  pResMat->PutDouble(pResMat->GetDouble(col)+fIntercept, col);
3219  }
3220  if (_bGrowth)
3221  {
3222  for (SCSIZE i = 0; i < nCXN; i++)
3223  pResMat->PutDouble(exp(pResMat->GetDouble(i)), i);
3224  }
3225  }
3226  }
3227  PushMatrix(pResMat);
3228 }
3229 
3231 {
3232  // In case it contains relative references resolve them as usual.
3233  Push( *pCur );
3234  ScAddress aAdr;
3235  PopSingleRef( aAdr );
3236 
3237  ScRefCellValue aCell(mrDoc, aAdr);
3238 
3239  if (aCell.meType != CELLTYPE_FORMULA)
3240  {
3241  PushError( FormulaError::NoRef );
3242  return;
3243  }
3244 
3245  if (aCell.mpFormula->IsRunning())
3246  {
3247  // Twisted odd corner case where an array element's cell tries to
3248  // access the top left matrix while it is still running, see tdf#88737
3249  // This is a hackish workaround, not a general solution, the matrix
3250  // isn't available anyway and FormulaError::CircularReference would be set.
3251  PushError( FormulaError::RetryCircular );
3252  return;
3253  }
3254 
3255  const ScMatrix* pMat = aCell.mpFormula->GetMatrix();
3256  if (pMat)
3257  {
3258  SCSIZE nCols, nRows;
3259  pMat->GetDimensions( nCols, nRows );
3260  SCSIZE nC = static_cast<SCSIZE>(aPos.Col() - aAdr.Col());
3261  SCSIZE nR = static_cast<SCSIZE>(aPos.Row() - aAdr.Row());
3262  if ((nCols <= nC && nCols != 1) || (nRows <= nR && nRows != 1))
3263  PushNA();
3264  else
3265  {
3266  const ScMatrixValue nMatVal = pMat->Get( nC, nR);
3267  ScMatValType nMatValType = nMatVal.nType;
3268 
3269  if (ScMatrix::IsNonValueType( nMatValType))
3270  {
3271  if (ScMatrix::IsEmptyPathType( nMatValType))
3272  { // result of empty false jump path
3273  nFuncFmtType = SvNumFormatType::LOGICAL;
3274  PushInt(0);
3275  }
3276  else if (ScMatrix::IsEmptyType( nMatValType))
3277  {
3278  // Not inherited (really?) and display as empty string, not 0.
3279  PushTempToken( new ScEmptyCellToken( false, true));
3280  }
3281  else
3282  PushString( nMatVal.GetString() );
3283  }
3284  else
3285  {
3286  // Determine nFuncFmtType type before PushDouble().
3287  mrDoc.GetNumberFormatInfo(mrContext, nCurFmtType, nCurFmtIndex, aAdr);
3288  nFuncFmtType = nCurFmtType;
3289  nFuncFmtIndex = nCurFmtIndex;
3290  PushDouble(nMatVal.fVal); // handles DoubleError
3291  }
3292  }
3293  }
3294  else
3295  {
3296  // Determine nFuncFmtType type before PushDouble().
3297  mrDoc.GetNumberFormatInfo(mrContext, nCurFmtType, nCurFmtIndex, aAdr);
3298  nFuncFmtType = nCurFmtType;
3299  nFuncFmtIndex = nCurFmtIndex;
3300  // If not a result matrix, obtain the cell value.
3301  FormulaError nErr = aCell.mpFormula->GetErrCode();
3302  if (nErr != FormulaError::NONE)
3303  PushError( nErr );
3304  else if (aCell.mpFormula->IsValue())
3305  PushDouble(aCell.mpFormula->GetValue());
3306  else
3307  {
3308  svl::SharedString aVal = aCell.mpFormula->GetString();
3309  PushString( aVal );
3310  }
3311  }
3312 }
3313 
3315 {
3316  if( !MustHaveParamCount( GetByte(), 1 ) )
3317  return;
3318 
3319  OUString aStr = GetString().getString();
3321  if( aStr == "SYSTEM" )
3322  PushString( SC_INFO_OSVERSION );
3323  else if( aStr == "OSVERSION" )
3324  PushString( "Windows (32-bit) NT 5.01" );
3325  else if( aStr == "RELEASE" )
3326  PushString( ::utl::Bootstrap::getBuildIdData( OUString() ) );
3327  else if( aStr == "NUMFILE" )
3328  PushDouble( 1 );
3329  else if( aStr == "RECALC" )
3330  PushString( ScResId( mrDoc.GetAutoCalc() ? STR_RECALC_AUTO : STR_RECALC_MANUAL ) );
3331  else if (aStr == "DIRECTORY" || aStr == "MEMAVAIL" || aStr == "MEMUSED" || aStr == "ORIGIN" || aStr == "TOTMEM")
3332  PushNA();
3333  else
3334  PushIllegalArgument();
3335 }
3336 
3337 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
static bool IsNonValueType(ScMatValType nType)
String, empty or empty path, but not value nor boolean.
Definition: scmatrix.hxx:173
Matrix data type that can store values of mixed types.
Definition: scmatrix.hxx:113
void ScGCD()
Definition: interpr5.cxx:129
void ScFrequency()
Definition: interpr5.cxx:1880
void CalculateMatrixValue(const ScMatrix *pMat, SCSIZE nC, SCSIZE nR)
Definition: interpr5.cxx:707
OUString getString() const
void CalculateAddSub(bool _bSub)
Definition: interpr5.cxx:1279
SCROW Row() const
Definition: address.hxx:262
void ScLCM()
Definition: interpr5.cxx:203
void ScEMat()
Definition: interpr5.cxx:730
void CalculateSumX2MY2SumX2DY2(bool _bSumX2DY2)
Definition: interpr5.cxx:1801
int SetError()
static void lcl_LUP_solve(const ScMatrix *mLU, const SCSIZE n, const ::std::vector< SCSIZE > &P, const ::std::vector< double > &B,::std::vector< double > &X)
Definition: interpr5.cxx:880
void ScLogest()
Definition: interpr5.cxx:2403
void PutDouble(double fVal, SCSIZE nC, SCSIZE nR)
Definition: scmatrix.cxx:2999
bool mbError
ScMatrixRef GetMatrix()
Definition: interpr5.cxx:478
sal_uIntPtr sal_uLong
ScMatrixValue Get(SCSIZE nC, SCSIZE nR) const
: If bString the ScMatrixValue->pS may still be NULL to indicate an empty string! ...
Definition: scmatrix.cxx:3084
Abstract base class for vectorised formula group interpreters, plus a global instance factory...
#define N
static ScMatrixRef lcl_MatrixCalculation(const ScMatrix &rMat1, const ScMatrix &rMat2, ScInterpreter *pInterpreter)
Definition: interpr5.cxx:1168
static FormulaGroupInterpreter * getStatic()
load and/or configure the correct formula group interpreter
void CalculateRGPRKP(bool _bRKP)
Definition: interpr5.cxx:2408
This is very similar to ScCellValue, except that it references the original value instead of copying ...
Definition: cellvalue.hxx:104
void ScSumProduct()
Definition: interpr5.cxx:1749
FormulaError GetErrorIfNotString(SCSIZE nC, SCSIZE nR) const
Use in ScInterpreter to obtain the error code, if any.
Definition: scmatrix.hxx:290
Try NOT to use this struct.
Definition: scmatrix.hxx:53
double GetDouble(SCSIZE nC, SCSIZE nR) const
Definition: scmatrix.cxx:3054
OUString GetString(int nId)
tuple log
double fVal
Definition: scmatrix.hxx:55
char sal_uInt16 & nParamCount
Definition: callform.cxx:53
Op_< std::function< void(double &, double)>> Op
static css::lang::Locale * GetLocale()
Definition: global.cxx:1048
static SCSIZE lcl_GetMinExtent(SCSIZE n1, SCSIZE n2)
Minimum extent of one result matrix dimension.
Definition: interpr5.cxx:1155
size_t SCSIZE
size_t typedef to be able to find places where code was changed from USHORT to size_t and is used to ...
Definition: address.hxx:45
const BorderLinePrimitive2D *pCandidateB assert(pCandidateA)
ScMatrixRef GetNewMat(SCSIZE nC, SCSIZE nR, bool bEmpty=false)
Definition: interpr5.cxx:298
void ScMatTrans()
Definition: interpr5.cxx:1127
double GetValue()
FormulaError GetErrCode()
int nCount
const ScRefCellValue & getRefCellValue() const
Definition: dociter.hxx:242
::boost::intrusive_ptr< ScMatrix > ScMatrixRef
Definition: types.hxx:26
Walk through all cells in an area.
Definition: dociter.hxx:208
ScFormulaCell * mpFormula
Definition: cellvalue.hxx:111
bool IsStringOrEmpty(SCSIZE nIndex) const
Definition: scmatrix.cxx:3089
bool hasEmptyValue()
Definition: cellvalue.cxx:675
FormulaError GetDoubleErrorValue(double fVal)
void ScMatDet()
Definition: interpr5.cxx:919
void ScLinest()
Definition: interpr5.cxx:2397
static void lcl_GetDiffDateTimeFmtType(SvNumFormatType &nFuncFmt, SvNumFormatType nFmt1, SvNumFormatType nFmt2)
Definition: interpr5.cxx:1247
double d
void MakeMatNew(ScMatrixRef &rMat, SCSIZE nC, SCSIZE nR)
Definition: interpr5.cxx:283
ocInfo
static bool IsEmptyType(ScMatValType nType)
Empty, but not empty path or any other type.
Definition: scmatrix.hxx:187
static double div(const double &fNumerator, const double &fDenominator)
Fail safe division, returning a FormulaError::DivisionByZero coded into a double if denominator is 0...
Definition: interpre.hxx:1157
double ConvertStringToValue(const OUString &)
Definition: interpr4.cxx:160
virtual const ScComplexRefData * GetDoubleRef() const
static bool IsEmptyPathType(ScMatValType nType)
Empty path, but not empty or any other type.
Definition: scmatrix.hxx:193
int i
svl::SharedString GetString(SCSIZE nC, SCSIZE nR) const
Definition: scmatrix.cxx:3069
void GetDimensions(SCSIZE &rC, SCSIZE &rR) const
Definition: scmatrix.cxx:2974
sal_Int16 SCCOL
Definition: types.hxx:22
const SCSIZE SCSIZE_MAX
Definition: address.hxx:60
ScMatrixRef CreateMatrixFromDoubleRef(const formula::FormulaToken *pToken, SCCOL nCol1, SCROW nRow1, SCTAB nTab1, SCCOL nCol2, SCROW nRow2, SCTAB nTab2)
Definition: interpr5.cxx:316
void ScMatValue()
Definition: interpr5.cxx:629
void ScAmpersand()
Definition: interpr5.cxx:1407
OUString ScResId(const char *pId)
Definition: scdll.cxx:89
svExternalDoubleRef
SvNumFormatType
svExternalSingleRef
bool IsTrimToData() const
Definition: refdata.hxx:202
bool IsRunning() const
bool hasNumeric() const
Definition: cellvalue.cxx:622
void GetVars(SCCOL &nCol1, SCROW &nRow1, SCTAB &nTab1, SCCOL &nCol2, SCROW &nRow2, SCTAB &nTab2) const
Definition: address.hxx:693
virtual ScMatrixRef inverseMatrix(const ScMatrix &rMat)=0
css::beans::Optional< css::uno::Any > getValue(std::u16string_view id)
ScMatrixRef mpMat
Definition: types.hxx:85
bool CheckMatrix(bool _bLOG, sal_uInt8 &nCase, SCSIZE &nCX, SCSIZE &nCY, SCSIZE &nRX, SCSIZE &nRY, SCSIZE &M, SCSIZE &N, ScMatrixRef &pMatX, ScMatrixRef &pMatY)
Definition: interpr5.cxx:2291
ScMatValType nType
Definition: scmatrix.hxx:57
const NodeContext & mrContext
const svl::SharedString & GetString()
FormulaError
SCCOL Col() const
Definition: address.hxx:267
bool isEmpty() const
Definition: dociter.cxx:1019
void CalculateTrendGrowth(bool _bGrowth)
Definition: interpr5.cxx:2932
static bool isOpenCLEnabled()
Definition: calcconfig.cxx:69
double power(const double &fVal1, const double &fVal2)
Return pow(fVal1,fVal2) with error handling.
Definition: math.cxx:29
const ScAddress & GetPos() const
Definition: dociter.hxx:234
const svl::SharedString & GetString() const
Only valid if ScMatrix methods indicate so!
Definition: scmatrix.hxx:60
void ScMatRef()
Definition: interpr5.cxx:3230
CellType meType
Definition: cellvalue.hxx:106
::formula::FormulaTokenRef TokenRef
sal_Int32 SCROW
Definition: types.hxx:18
static void transKeyword(OUString &rName, const css::lang::Locale *pLocale, OpCode eOpCode)
double CreateDoubleError(FormulaError nErr)
static int lcl_LUP_decompose(ScMatrix *mA, const SCSIZE n,::std::vector< SCSIZE > &P)
Definition: interpr5.cxx:779
void ScSumX2DY2()
Definition: interpr5.cxx:1841
unsigned char sal_uInt8
void ScMatInv()
Definition: interpr5.cxx:966
bool GetFirst(double &rValue, FormulaError &rErr)
Does NOT reset rValue if no value found!
Definition: dociter.cxx:285
void ScTrend()
Definition: interpr5.cxx:2922
ScMatValType
Definition: types.hxx:32
const ScMatrix * GetMatrix()
ScMatrixRef MatConcat(const ScMatrixRef &pMat1, const ScMatrixRef &pMat2)
Definition: interpr5.cxx:1230
void * p
When adding all numerical matrix elements for a scalar result such as summation, the interpreter want...
Definition: scmatrix.hxx:144
double getValue()
Definition: cellvalue.cxx:632
void ScPower()
Definition: interpr5.cxx:1658
bool GetNext(double &rValue, FormulaError &rErr)
Does NOT reset rValue if no value found!
Definition: dociter.cxx:309
void ScSumX2MY2()
Definition: interpr5.cxx:1797
void ScSumXMY2()
Definition: interpr5.cxx:1846
Complex reference (a range) into the sheet.
Definition: refdata.hxx:123
sc::RangeMatrix GetRangeMatrix()
Definition: interpr5.cxx:615
void ScGrowth()
Definition: interpr5.cxx:2927
static void MEMat(const ScMatrixRef &mM, SCSIZE n)
Definition: interpr5.cxx:753
aStr
static OUString getBuildIdData(OUString const &_sDefault)
bool IsValueOrEmpty(SCSIZE nC, SCSIZE nR) const
Definition: scmatrix.cxx:3129
double div(const double &fNumerator, const double &fDenominator)
Return fNumerator/fDenominator if fDenominator!=0 else #DIV/0! error coded into double.
Definition: math.hxx:31
static double ScGetGCD(double fx, double fy)
Definition: interpr5.cxx:108
static bool IsSizeAllocatable(SCSIZE nC, SCSIZE nR)
Checks nC or nR for zero and uses GetElementsMax() whether a matrix of the size of nC*nR could be all...
Definition: scmatrix.cxx:2846
sal_Int16 SCTAB
Definition: types.hxx:23
void ScMatMult()
Definition: interpr5.cxx:1078