source: trunk/MagicSoft/Mars/mbase/MMath.cc@ 9223

Last change on this file since 9223 was 9219, checked in by tbretz, 16 years ago
*** empty log message ***
File size: 25.4 KB
Line 
1/* ======================================================================== *\
2! $Name: not supported by cvs2svn $:$Id: MMath.cc,v 1.43 2009-01-14 12:31:36 tbretz Exp $
3! --------------------------------------------------------------------------
4!
5! *
6! * This file is part of MARS, the MAGIC Analysis and Reconstruction
7! * Software. It is distributed to you in the hope that it can be a useful
8! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
9! * It is distributed WITHOUT ANY WARRANTY.
10! *
11! * Permission to use, copy, modify and distribute this software and its
12! * documentation for any purpose is hereby granted without fee,
13! * provided that the above copyright notice appear in all copies and
14! * that both that copyright notice and this permission notice appear
15! * in supporting documentation. It is provided "as is" without express
16! * or implied warranty.
17! *
18!
19!
20! Author(s): Thomas Bretz 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
21!
22! Copyright: MAGIC Software Development, 2000-2005
23!
24!
25\* ======================================================================== */
26
27/////////////////////////////////////////////////////////////////////////////
28//
29// MMath
30//
31// Mars - Math package (eg Significances, etc)
32//
33/////////////////////////////////////////////////////////////////////////////
34#include "MMath.h"
35
36#include <stdlib.h> // atof (Ubuntu 8.10)
37
38#ifndef ROOT_TVector2
39#include <TVector2.h>
40#endif
41
42#ifndef ROOT_TVector3
43#include <TVector3.h>
44#endif
45
46#ifndef ROOT_TArrayD
47#include <TArrayD.h>
48#endif
49
50#ifndef ROOT_TComplex
51#include <TComplex.h>
52#endif
53
54//NamespaceImp(MMath);
55
56// --------------------------------------------------------------------------
57//
58// Calculate Significance as
59// significance = (s-b)/sqrt(s+k*k*b) mit k=s/b
60//
61// s: total number of events in signal region
62// b: number of background events in signal region
63//
64Double_t MMath::Significance(Double_t s, Double_t b)
65{
66 const Double_t k = b==0 ? 0 : s/b;
67 const Double_t f = s+k*k*b;
68
69 return f==0 ? 0 : (s-b)/TMath::Sqrt(f);
70}
71
72// --------------------------------------------------------------------------
73//
74// Symmetrized significance - this is somehow analog to
75// SignificanceLiMaSigned
76//
77// Returns Significance(s,b) if s>b otherwise -Significance(b, s);
78//
79Double_t MMath::SignificanceSym(Double_t s, Double_t b)
80{
81 return s>b ? Significance(s, b) : -Significance(b, s);
82}
83
84// --------------------------------------------------------------------------
85//
86// calculates the significance according to Li & Ma
87// ApJ 272 (1983) 317, Formula 17
88//
89// s // s: number of on events
90// b // b: number of off events
91// alpha = t_on/t_off; // t: observation time
92//
93// The significance has the same (positive!) value for s>b and b>s.
94//
95// Returns -1 if s<0 or b<0 or alpha<0 or the argument of sqrt<0
96//
97// Here is some eMail written by Daniel Mazin about the meaning of the arguments:
98//
99// > Ok. Here is my understanding:
100// > According to Li&Ma paper (correctly cited in MMath.cc) alpha is the
101// > scaling factor. The mathematics behind the formula 17 (and/or 9) implies
102// > exactly this. If you scale OFF to ON first (using time or using any other
103// > method), then you cannot use formula 17 (9) anymore. You can just try
104// > the formula before scaling (alpha!=1) and after scaling (alpha=1), you
105// > will see the result will be different.
106//
107// > Here are less mathematical arguments:
108//
109// > 1) the better background determination you have (smaller alpha) the more
110// > significant is your excess, thus your analysis is more sensitive. If you
111// > normalize OFF to ON first, you loose this sensitivity.
112//
113// > 2) the normalization OFF to ON has an error, which naturally depends on
114// > the OFF and ON. This error is propagating to the significance of your
115// > excess if you use the Li&Ma formula 17 correctly. But if you normalize
116// > first and use then alpha=1, the error gets lost completely, you loose
117// > somehow the criteria of goodness of the normalization.
118//
119Double_t MMath::SignificanceLiMa(Double_t s, Double_t b, Double_t alpha)
120{
121 const Double_t sum = s+b;
122
123 if (s<0 || b<0 || alpha<=0)
124 return -1;
125
126 const Double_t l = s==0 ? 0 : s*TMath::Log(s/sum*(alpha+1)/alpha);
127 const Double_t m = b==0 ? 0 : b*TMath::Log(b/sum*(alpha+1) );
128
129 return l+m<0 ? -1 : TMath::Sqrt((l+m)*2);
130}
131
132/*
133Double_t MMath::SignificanceLiMaErr(Double_t s, Double_t b, Double_t alpha)
134{
135 Double_t S = SignificanceLiMa(s, b, alpha);
136 if (S<0)
137 return -1;
138
139 const Double_t sum = s+b;
140
141
142 Double_t l = TMath::Log(s/sum*(alpha+1)/alpha)/TMath::Sqrt(2*S);
143 Double_t m = TMath::Log(s/sum*(alpha+1)/alpha)/TMath::Sqrt(2*S);
144
145
146 const Double_t sum = s+b;
147
148 if (s<0 || b<0 || alpha<=0)
149 return -1;
150
151 const Double_t l = s==0 ? 0 : s*TMath::Log(s/sum*(alpha+1)/alpha);
152 const Double_t m = b==0 ? 0 : b*TMath::Log(b/sum*(alpha+1) );
153
154 return l+m<0 ? -1 : TMath::Sqrt((l+m)*2);
155}
156*/
157
158// --------------------------------------------------------------------------
159//
160// Calculates MMath::SignificanceLiMa(s, b, alpha). Returns 0 if the
161// calculation has failed. Otherwise the Li/Ma significance which was
162// calculated. If s<b a negative value is returned.
163//
164Double_t MMath::SignificanceLiMaSigned(Double_t s, Double_t b, Double_t alpha)
165{
166 const Double_t sig = SignificanceLiMa(s, b, alpha);
167 if (sig<=0)
168 return 0;
169
170 return TMath::Sign(sig, s-alpha*b);
171}
172
173// --------------------------------------------------------------------------
174//
175// Return Li/Ma (5) for the error of the excess, under the assumption that
176// the existance of a signal is already known. (basically signal/error
177// calculated by error propagation)
178//
179Double_t MMath::SignificanceExc(Double_t s, Double_t b, Double_t alpha)
180{
181 const Double_t error = ErrorExc(s, b, alpha);
182 if (error==0)
183 return 0;
184
185 const Double_t Ns = s - alpha*b;
186
187 return Ns/error;
188}
189
190// --------------------------------------------------------------------------
191//
192// Calculate the error of s-alpha*b by error propagation
193//
194Double_t MMath::ErrorExc(Double_t s, Double_t b, Double_t alpha)
195{
196 const Double_t sN = s + alpha*alpha*b;
197 return sN<0 ? 0 : TMath::Sqrt(sN);
198}
199
200// --------------------------------------------------------------------------
201//
202// Returns: 2/(sigma*sqrt(2))*integral[0,x](exp(-(x-mu)^2/(2*sigma^2)))
203//
204Double_t MMath::GaussProb(Double_t x, Double_t sigma, Double_t mean)
205{
206 if (x<mean)
207 return 0;
208
209 static const Double_t sqrt2 = TMath::Sqrt(2.);
210
211 const Double_t rc = TMath::Erf((x-mean)/(sigma*sqrt2));
212
213 if (rc<0)
214 return 0;
215 if (rc>1)
216 return 1;
217
218 return rc;
219}
220
221// ------------------------------------------------------------------------
222//
223// Return the "median" (at 68.3%) value of the distribution of
224// abs(a[i]-Median)
225//
226template <class Size, class Element>
227Double_t MMath::MedianDevImp(Size n, const Element *a, Double_t &med)
228{
229 static const Double_t prob = 0.682689477208650697; //MMath::GaussProb(1.0);
230
231 // Sanity check
232 if (n <= 0 || !a)
233 return 0;
234
235 // Get median of distribution
236 med = TMath::Median(n, a);
237
238 // Create the abs(a[i]-med) distribution
239 Double_t arr[n];
240 for (int i=0; i<n; i++)
241 arr[i] = TMath::Abs(a[i]-med);
242
243 //return TMath::Median(n, arr)/0.67449896936; //MMath::GaussProb(x)=0.5
244
245 // Define where to divide (floor because the highest possible is n-1)
246 const Size div = TMath::FloorNint(n*prob);
247
248 // Calculate result
249 Double_t dev = TMath::KOrdStat(n, arr, div);
250 if (n%2 == 0)
251 {
252 dev += TMath::KOrdStat(n, arr, div-1);
253 dev /= 2;
254 }
255
256 return dev;
257}
258
259// ------------------------------------------------------------------------
260//
261// Return the "median" (at 68.3%) value of the distribution of
262// abs(a[i]-Median)
263//
264Double_t MMath::MedianDev(Long64_t n, const Short_t *a, Double_t &med)
265{
266 return MedianDevImp(n, a, med);
267}
268
269// ------------------------------------------------------------------------
270//
271// Return the "median" (at 68.3%) value of the distribution of
272// abs(a[i]-Median)
273//
274Double_t MMath::MedianDev(Long64_t n, const Int_t *a, Double_t &med)
275{
276 return MedianDevImp(n, a, med);
277}
278
279// ------------------------------------------------------------------------
280//
281// Return the "median" (at 68.3%) value of the distribution of
282// abs(a[i]-Median)
283//
284Double_t MMath::MedianDev(Long64_t n, const Float_t *a, Double_t &med)
285{
286 return MedianDevImp(n, a, med);
287}
288
289// ------------------------------------------------------------------------
290//
291// Return the "median" (at 68.3%) value of the distribution of
292// abs(a[i]-Median)
293//
294Double_t MMath::MedianDev(Long64_t n, const Double_t *a, Double_t &med)
295{
296 return MedianDevImp(n, a, med);
297}
298
299// ------------------------------------------------------------------------
300//
301// Return the "median" (at 68.3%) value of the distribution of
302// abs(a[i]-Median)
303//
304Double_t MMath::MedianDev(Long64_t n, const Long_t *a, Double_t &med)
305{
306 return MedianDevImp(n, a, med);
307}
308
309// ------------------------------------------------------------------------
310//
311// Return the "median" (at 68.3%) value of the distribution of
312// abs(a[i]-Median)
313//
314Double_t MMath::MedianDev(Long64_t n, const Long64_t *a, Double_t &med)
315{
316 return MedianDevImp(n, a, med);
317}
318
319Double_t MMath::MedianDev(Long64_t n, const Short_t *a) { Double_t med; return MedianDevImp(n, a, med); }
320Double_t MMath::MedianDev(Long64_t n, const Int_t *a) { Double_t med; return MedianDevImp(n, a, med); }
321Double_t MMath::MedianDev(Long64_t n, const Float_t *a) { Double_t med; return MedianDevImp(n, a, med); }
322Double_t MMath::MedianDev(Long64_t n, const Double_t *a) { Double_t med; return MedianDevImp(n, a, med); }
323Double_t MMath::MedianDev(Long64_t n, const Long_t *a) { Double_t med; return MedianDevImp(n, a, med); }
324Double_t MMath::MedianDev(Long64_t n, const Long64_t *a) { Double_t med; return MedianDevImp(n, a, med); }
325
326// ------------------------------------------------------------------------
327//
328// Re-sort an array. Intsead of returning an index (like TMath::Sort)
329// the array contents are sorted.
330//
331template <class Size, class Element> void MMath::ReSortImp(Size n, Element *a, Bool_t down)
332{
333 Element *cpy = new Element[n];
334 Int_t *pos = new Int_t[n];
335
336 memcpy(cpy, a, n*sizeof(Element));
337
338 TMath::Sort(n, a, pos, down);
339
340 Int_t *idx = pos;
341
342 for (Element *ptr=a; ptr<a+n; ptr++)
343 *ptr = cpy[*idx++];
344
345 delete cpy;
346 delete pos;
347}
348
349void MMath::ReSort(Long64_t n, Short_t *a, Bool_t down) { ReSortImp(n, a, down); }
350void MMath::ReSort(Long64_t n, Int_t *a, Bool_t down) { ReSortImp(n, a, down); }
351void MMath::ReSort(Long64_t n, Float_t *a, Bool_t down) { ReSortImp(n, a, down); }
352void MMath::ReSort(Long64_t n, Double_t *a, Bool_t down) { ReSortImp(n, a, down); }
353
354// --------------------------------------------------------------------------
355//
356// This function reduces the precision to roughly 0.5% of a Float_t by
357// changing its bit-pattern (Be carefull, in rare cases this function must
358// be adapted to different machines!). This is usefull to enforce better
359// compression by eg. gzip.
360//
361void MMath::ReducePrecision(Float_t &val)
362{
363 UInt_t &f = (UInt_t&)val;
364
365 f += 0x00004000;
366 f &= 0xffff8000;
367}
368
369// -------------------------------------------------------------------------
370//
371// Quadratic interpolation
372//
373// calculate the parameters of a parabula such that
374// y(i) = a + b*x(i) + c*x(i)^2
375//
376// If the determinant==0 an empty TVector3 is returned.
377//
378TVector3 MMath::GetParab(const TVector3 &x, const TVector3 &y)
379{
380 const Double_t x1 = x(0);
381 const Double_t x2 = x(1);
382 const Double_t x3 = x(2);
383
384 const Double_t y1 = y(0);
385 const Double_t y2 = y(1);
386 const Double_t y3 = y(2);
387
388 const double det =
389 + x2*x3*x3 + x1*x2*x2 + x3*x1*x1
390 - x2*x1*x1 - x3*x2*x2 - x1*x3*x3;
391
392
393 if (det==0)
394 return TVector3();
395
396 const double det1 = 1.0/det;
397
398 const double ai11 = x2*x3*x3 - x3*x2*x2;
399 const double ai12 = x3*x1*x1 - x1*x3*x3;
400 const double ai13 = x1*x2*x2 - x2*x1*x1;
401
402 const double ai21 = x2*x2 - x3*x3;
403 const double ai22 = x3*x3 - x1*x1;
404 const double ai23 = x1*x1 - x2*x2;
405
406 const double ai31 = x3 - x2;
407 const double ai32 = x1 - x3;
408 const double ai33 = x2 - x1;
409
410 return TVector3((ai11*y1 + ai12*y2 + ai13*y3) * det1,
411 (ai21*y1 + ai22*y2 + ai23*y3) * det1,
412 (ai31*y1 + ai32*y2 + ai33*y3) * det1);
413}
414
415// --------------------------------------------------------------------------
416//
417// Interpolate the points with x-coordinates vx and y-coordinates vy
418// by a parabola (second order polynomial) and return the value at x.
419//
420Double_t MMath::InterpolParabLin(const TVector3 &vx, const TVector3 &vy, Double_t x)
421{
422 const TVector3 c = GetParab(vx, vy);
423 return c(0) + c(1)*x + c(2)*x*x;
424}
425
426// --------------------------------------------------------------------------
427//
428// Interpolate the points with x-coordinates vx=(-1,0,1) and
429// y-coordinates vy by a parabola (second order polynomial) and return
430// the value at x.
431//
432Double_t MMath::InterpolParabLin(const TVector3 &vy, Double_t x)
433{
434 const TVector3 c(vy(1), (vy(2)-vy(0))/2, vy(0)/2 - vy(1) + vy(2)/2);
435 return c(0) + c(1)*x + c(2)*x*x;
436}
437
438Double_t MMath::InterpolParabLog(const TVector3 &vx, const TVector3 &vy, Double_t x)
439{
440 const Double_t l0 = TMath::Log10(vx(0));
441 const Double_t l1 = TMath::Log10(vx(1));
442 const Double_t l2 = TMath::Log10(vx(2));
443
444 const TVector3 vx0(l0, l1, l2);
445 return InterpolParabLin(vx0, vy, TMath::Log10(x));
446}
447
448Double_t MMath::InterpolParabCos(const TVector3 &vx, const TVector3 &vy, Double_t x)
449{
450 const Double_t l0 = TMath::Cos(vx(0));
451 const Double_t l1 = TMath::Cos(vx(1));
452 const Double_t l2 = TMath::Cos(vx(2));
453
454 const TVector3 vx0(l0, l1, l2);
455 return InterpolParabLin(vx0, vy, TMath::Cos(x));
456}
457
458// --------------------------------------------------------------------------
459//
460// Analytically calculated result of a least square fit of:
461// y = A*e^(B*x)
462// Equal weights
463//
464// It returns TArrayD(2) = { A, B };
465//
466// see: http://mathworld.wolfram.com/LeastSquaresFittingExponential.html
467//
468TArrayD MMath::LeastSqFitExpW1(Int_t n, Double_t *x, Double_t *y)
469{
470 Double_t sumxsqy = 0;
471 Double_t sumylny = 0;
472 Double_t sumxy = 0;
473 Double_t sumy = 0;
474 Double_t sumxylny = 0;
475 for (int i=0; i<n; i++)
476 {
477 sumylny += y[i]*TMath::Log(y[i]);
478 sumxy += x[i]*y[i];
479 sumxsqy += x[i]*x[i]*y[i];
480 sumxylny += x[i]*y[i]*TMath::Log(y[i]);
481 sumy += y[i];
482 }
483
484 const Double_t dev = sumy*sumxsqy - sumxy*sumxy;
485
486 const Double_t a = (sumxsqy*sumylny - sumxy*sumxylny)/dev;
487 const Double_t b = (sumy*sumxylny - sumxy*sumylny)/dev;
488
489 TArrayD rc(2);
490 rc[0] = TMath::Exp(a);
491 rc[1] = b;
492 return rc;
493}
494
495// --------------------------------------------------------------------------
496//
497// Analytically calculated result of a least square fit of:
498// y = A*e^(B*x)
499// Greater weights to smaller values
500//
501// It returns TArrayD(2) = { A, B };
502//
503// see: http://mathworld.wolfram.com/LeastSquaresFittingExponential.html
504//
505TArrayD MMath::LeastSqFitExp(Int_t n, Double_t *x, Double_t *y)
506{
507 // -------- Greater weights to smaller values ---------
508 Double_t sumlny = 0;
509 Double_t sumxlny = 0;
510 Double_t sumxsq = 0;
511 Double_t sumx = 0;
512 for (int i=0; i<n; i++)
513 {
514 sumlny += TMath::Log(y[i]);
515 sumxlny += x[i]*TMath::Log(y[i]);
516
517 sumxsq += x[i]*x[i];
518 sumx += x[i];
519 }
520
521 const Double_t dev = n*sumxsq-sumx*sumx;
522
523 const Double_t a = (sumlny*sumxsq - sumx*sumxlny)/dev;
524 const Double_t b = (n*sumxlny - sumx*sumlny)/dev;
525
526 TArrayD rc(2);
527 rc[0] = TMath::Exp(a);
528 rc[1] = b;
529 return rc;
530}
531
532// --------------------------------------------------------------------------
533//
534// Analytically calculated result of a least square fit of:
535// y = A+B*ln(x)
536//
537// It returns TArrayD(2) = { A, B };
538//
539// see: http://mathworld.wolfram.com/LeastSquaresFittingLogarithmic.html
540//
541TArrayD MMath::LeastSqFitLog(Int_t n, Double_t *x, Double_t *y)
542{
543 Double_t sumylnx = 0;
544 Double_t sumy = 0;
545 Double_t sumlnx = 0;
546 Double_t sumlnxsq = 0;
547 for (int i=0; i<n; i++)
548 {
549 sumylnx += y[i]*TMath::Log(x[i]);
550 sumy += y[i];
551 sumlnx += TMath::Log(x[i]);
552 sumlnxsq += TMath::Log(x[i])*TMath::Log(x[i]);
553 }
554
555 const Double_t b = (n*sumylnx-sumy*sumlnx)/(n*sumlnxsq-sumlnx*sumlnx);
556 const Double_t a = (sumy-b*sumlnx)/n;
557
558 TArrayD rc(2);
559 rc[0] = a;
560 rc[1] = b;
561 return rc;
562}
563
564// --------------------------------------------------------------------------
565//
566// Analytically calculated result of a least square fit of:
567// y = A*x^B
568//
569// It returns TArrayD(2) = { A, B };
570//
571// see: http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html
572//
573TArrayD MMath::LeastSqFitPowerLaw(Int_t n, Double_t *x, Double_t *y)
574{
575 Double_t sumlnxlny = 0;
576 Double_t sumlnx = 0;
577 Double_t sumlny = 0;
578 Double_t sumlnxsq = 0;
579 for (int i=0; i<n; i++)
580 {
581 sumlnxlny += TMath::Log(x[i])*TMath::Log(y[i]);
582 sumlnx += TMath::Log(x[i]);
583 sumlny += TMath::Log(y[i]);
584 sumlnxsq += TMath::Log(x[i])*TMath::Log(x[i]);
585 }
586
587 const Double_t b = (n*sumlnxlny-sumlnx*sumlny)/(n*sumlnxsq-sumlnx*sumlnx);
588 const Double_t a = (sumlny-b*sumlnx)/n;
589
590 TArrayD rc(2);
591 rc[0] = TMath::Exp(a);
592 rc[1] = b;
593 return rc;
594}
595
596// --------------------------------------------------------------------------
597//
598// Calculate the intersection of two lines defined by (x1;y1) and (x2;x2)
599// Returns the intersection point.
600//
601// It is assumed that the lines intersect. If there is no intersection
602// TVector2() is returned (which is not destinguishable from
603// TVector2(0,0) if the intersection is at the coordinate source)
604//
605// Formula from: http://mathworld.wolfram.com/Line-LineIntersection.html
606//
607TVector2 MMath::GetIntersectionPoint(const TVector2 &x1, const TVector2 &y1, const TVector2 &x2, const TVector2 &y2)
608{
609 TMatrix d(2,2);
610 d[0][0] = x1.X()-y1.X();
611 d[0][1] = x2.X()-y2.X();
612 d[1][0] = x1.Y()-y1.Y();
613 d[1][1] = x2.Y()-y2.Y();
614
615 const Double_t denom = d.Determinant();
616 if (denom==0)
617 return TVector2();
618
619 TMatrix l1(2,2);
620 TMatrix l2(2,2);
621
622 l1[0][0] = x1.X();
623 l1[0][1] = y1.X();
624 l2[0][0] = x2.X();
625 l2[0][1] = y2.X();
626
627 l1[1][0] = x1.Y();
628 l1[1][1] = y1.Y();
629 l2[1][0] = x2.Y();
630 l2[1][1] = y2.Y();
631
632 TMatrix a(2,2);
633 a[0][0] = l1.Determinant();
634 a[0][1] = l2.Determinant();
635 a[1][0] = x1.X()-y1.X();
636 a[1][1] = x2.X()-y2.X();
637
638 const Double_t X = a.Determinant()/denom;
639
640 a[1][0] = x1.Y()-y1.Y();
641 a[1][1] = x2.Y()-y2.Y();
642
643 const Double_t Y = a.Determinant()/denom;
644
645 return TVector2(X, Y);
646}
647
648// --------------------------------------------------------------------------
649//
650// Solves: x^2 + ax + b = 0;
651// Return number of solutions returned as x1, x2
652//
653Int_t MMath::SolvePol2(Double_t a, Double_t b, Double_t &x1, Double_t &x2)
654{
655 const Double_t r = a*a - 4*b;
656 if (r<0)
657 return 0;
658
659 if (r==0)
660 {
661 x1 = x2 = -a/2;
662 return 1;
663 }
664
665 const Double_t s = TMath::Sqrt(r);
666
667 x1 = (-a+s)/2;
668 x2 = (-a-s)/2;
669
670 return 2;
671}
672
673// --------------------------------------------------------------------------
674//
675// This is a helper function making the execution of SolverPol3 a bit faster
676//
677static inline Double_t ReMul(const TComplex &c1, const TComplex &th)
678{
679 const TComplex c2 = TComplex::Cos(th/3.);
680 return c1.Re() * c2.Re() - c1.Im() * c2.Im();
681}
682
683// --------------------------------------------------------------------------
684//
685// Solves: x^3 + ax^2 + bx + c = 0;
686// Return number of the real solutions, returned as z1, z2, z3
687//
688// Algorithm adapted from http://home.att.net/~srschmitt/cubizen.heml
689// Which is based on the solution given in
690// http://mathworld.wolfram.com/CubicEquation.html
691//
692// -------------------------------------------------------------------------
693//
694// Exact solutions of cubic polynomial equations
695// by Stephen R. Schmitt Algorithm
696//
697// An exact solution of the cubic polynomial equation:
698//
699// x^3 + a*x^2 + b*x + c = 0
700//
701// was first published by Gerolamo Cardano (1501-1576) in his treatise,
702// Ars Magna. He did not discoverer of the solution; a professor of
703// mathematics at the University of Bologna named Scipione del Ferro (ca.
704// 1465-1526) is credited as the first to find an exact solution. In the
705// years since, several improvements to the original solution have been
706// discovered. Zeno source code
707//
708// http://home.att.net/~srschmitt/cubizen.html
709//
710// % compute real or complex roots of cubic polynomial
711// function cubic( var z1, z2, z3 : real, a, b, c : real ) : real
712//
713// var Q, R, D, S, T : real
714// var im, th : real
715//
716// Q := (3*b - a^2)/9
717// R := (9*b*a - 27*c - 2*a^3)/54
718// D := Q^3 + R^2 % polynomial discriminant
719//
720// if (D >= 0) then % complex or duplicate roots
721//
722// S := sgn(R + sqrt(D))*abs(R + sqrt(D))^(1/3)
723// T := sgn(R - sqrt(D))*abs(R - sqrt(D))^(1/3)
724//
725// z1 := -a/3 + (S + T) % real root
726// z2 := -a/3 - (S + T)/2 % real part of complex root
727// z3 := -a/3 - (S + T)/2 % real part of complex root
728// im := abs(sqrt(3)*(S - T)/2) % complex part of root pair
729//
730// else % distinct real roots
731//
732// th := arccos(R/sqrt( -Q^3))
733//
734// z1 := 2*sqrt(-Q)*cos(th/3) - a/3
735// z2 := 2*sqrt(-Q)*cos((th + 2*pi)/3) - a/3
736// z3 := 2*sqrt(-Q)*cos((th + 4*pi)/3) - a/3
737// im := 0
738//
739// end if
740//
741// return im % imaginary part
742//
743// end function
744//
745// see also http://en.wikipedia.org/wiki/Cubic_equation
746//
747Int_t MMath::SolvePol3(Double_t a, Double_t b, Double_t c,
748 Double_t &x1, Double_t &x2, Double_t &x3)
749{
750 // Double_t coeff[4] = { 1, a, b, c };
751 // return TMath::RootsCubic(coeff, x1, x2, x3) ? 1 : 3;
752
753 const Double_t Q = (a*a - 3*b)/9;
754 const Double_t R = (9*b*a - 27*c - 2*a*a*a)/54;
755 const Double_t D = R*R - Q*Q*Q; // polynomial discriminant
756
757 // ----- The single-real / duplicate-roots solution -----
758
759 // D<0: three real roots
760 // D>0: one real root
761 // D==0: maximum two real roots (two identical roots)
762
763 // R==0: only one unique root
764 // R!=0: two roots
765
766 if (D==0)
767 {
768 const Double_t r = MMath::Sqrt3(R);
769
770 x1 = r - a/3.; // real root
771 if (R==0)
772 return 1;
773
774 x2 = 2*r - a/3.; // real root
775 return 2;
776 }
777
778 if (D>0) // complex or duplicate roots
779 {
780 const Double_t sqrtd = TMath::Sqrt(D);
781
782 const Double_t A = TMath::Sign(1., R)*MMath::Sqrt3(TMath::Abs(R)+sqrtd);
783
784 // The case A==0 cannot happen. This would imply D==0
785 // if (A==0)
786 // {
787 // x1 = -a/3;
788 // return 1;
789 // }
790
791 x1 = (A+Q/A)-a/3;
792
793 //const Double_t S = MMath::Sqrt3(R + sqrtd);
794 //const Double_t T = MMath::Sqrt3(R - sqrtd);
795 //x1 = (S+T) - a/3.; // real root
796
797 return 1;
798
799 //z2 = (S + T)/2 - a/3.; // real part of complex root
800 //z3 = (S + T)/2 - a/3.; // real part of complex root
801 //im = fabs(sqrt(3)*(S - T)/2) // complex part of root pair
802 }
803
804 // ----- The general solution with three roots ---
805
806 if (Q==0)
807 return 0;
808
809 if (Q>0) // This is here for speed reasons
810 {
811 const Double_t sqrtq = TMath::Sqrt(Q);
812 const Double_t rq = R/TMath::Abs(Q);
813
814 const Double_t t = TMath::ACos(rq/sqrtq)/3;
815
816 static const Double_t sqrt3 = TMath::Sqrt(3.);
817
818 const Double_t sn = TMath::Sin(t)*sqrt3;
819 const Double_t cs = TMath::Cos(t);
820
821 x1 = 2*sqrtq * cs - a/3;
822 x2 = -sqrtq * (sn + cs) - a/3;
823 x3 = sqrtq * (sn - cs) - a/3;
824
825 /* --- Easier to understand but slower ---
826 const Double_t th1 = TMath::ACos(rq/sqrtq);
827 const Double_t th2 = th1 + TMath::TwoPi();
828 const Double_t th3 = th2 + TMath::TwoPi();
829
830 x1 = 2.*sqrtq * TMath::Cos(th1/3.) - a/3.;
831 x2 = 2.*sqrtq * TMath::Cos(th2/3.) - a/3.;
832 x3 = 2.*sqrtq * TMath::Cos(th3/3.) - a/3.;
833 */
834 return 3;
835 }
836
837 const TComplex sqrtq = TComplex::Sqrt(Q);
838 const Double_t rq = R/TMath::Abs(Q);
839
840 const TComplex th1 = TComplex::ACos(rq/sqrtq);
841 const TComplex th2 = th1 + TMath::TwoPi();
842 const TComplex th3 = th2 + TMath::TwoPi();
843
844 // For ReMul, see bove
845 x1 = ReMul(2.*sqrtq, th1) - a/3.;
846 x2 = ReMul(2.*sqrtq, th2) - a/3.;
847 x3 = ReMul(2.*sqrtq, th3) - a/3.;
848
849 return 3;
850}
851
852// --------------------------------------------------------------------------
853//
854// Format a value and its error corresponding to the rules (note
855// this won't work if the error is more then eight orders smaller than
856// the value)
857//
858void MMath::Format(Double_t &v, Double_t &e)
859{
860 // Valid digits
861 Int_t i = TMath::FloorNint(TMath::Log10(v))-TMath::FloorNint(TMath::Log10(e));
862
863 // Check if error starts with 1 or 2. In this case use one
864 // more valid digit
865 TString error = Form("%.0e", e);
866 if (error[0]=='1' || error[0]=='2')
867 {
868 i++;
869 error = Form("%.1e", e);
870 }
871
872 const char *fmt = Form("%%.%de", i);
873
874 v = atof(Form(fmt, v));
875 e = error.Atof();
876}
Note: See TracBrowser for help on using the repository browser.