Updated core
[LibreOffice.git] / sal / rtl / math.cxx
blob3bca17156c3abc4e138d0e9be14a4c922bc29d94
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
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/.
9 * This file incorporates work covered by the following license notice:
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 .
21 #include "rtl/math.h"
23 #include "osl/diagnose.h"
24 #include "rtl/alloc.h"
25 #include "rtl/character.hxx"
26 #include "rtl/math.hxx"
27 #include "rtl/strbuf.h"
28 #include "rtl/string.h"
29 #include "rtl/ustrbuf.h"
30 #include "rtl/ustring.h"
31 #include "sal/mathconf.h"
32 #include "sal/types.h"
34 #include <algorithm>
35 #include <float.h>
36 #include <limits.h>
37 #include <math.h>
38 #include <stdlib.h>
41 static int const n10Count = 16;
42 static double const n10s[2][n10Count] = {
43 { 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8,
44 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16 },
45 { 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8,
46 1e-9, 1e-10, 1e-11, 1e-12, 1e-13, 1e-14, 1e-15, 1e-16 }
49 // return pow(10.0,nExp) optimized for exponents in the interval [-16,16]
50 static double getN10Exp( int nExp )
52 if ( nExp < 0 )
54 // && -nExp > 0 necessary for std::numeric_limits<int>::min()
55 // because -nExp = nExp
56 if ( -nExp <= n10Count && -nExp > 0 )
57 return n10s[1][-nExp-1];
58 else
59 return pow( 10.0, static_cast<double>( nExp ) );
61 else if ( nExp > 0 )
63 if ( nExp <= n10Count )
64 return n10s[0][nExp-1];
65 else
66 return pow( 10.0, static_cast<double>( nExp ) );
68 else // ( nExp == 0 )
69 return 1.0;
72 /** Approximation algorithm for erf for 0 < x < 0.65. */
73 static void lcl_Erf0065( double x, double& fVal )
75 static const double pn[] = {
76 1.12837916709551256,
77 1.35894887627277916E-1,
78 4.03259488531795274E-2,
79 1.20339380863079457E-3,
80 6.49254556481904354E-5
82 static const double qn[] = {
83 1.00000000000000000,
84 4.53767041780002545E-1,
85 8.69936222615385890E-2,
86 8.49717371168693357E-3,
87 3.64915280629351082E-4
89 double fPSum = 0.0;
90 double fQSum = 0.0;
91 double fXPow = 1.0;
92 for ( unsigned int i = 0; i <= 4; ++i )
94 fPSum += pn[i]*fXPow;
95 fQSum += qn[i]*fXPow;
96 fXPow *= x*x;
98 fVal = x * fPSum / fQSum;
101 /** Approximation algorithm for erfc for 0.65 < x < 6.0. */
102 static void lcl_Erfc0600( double x, double& fVal )
104 double fPSum = 0.0;
105 double fQSum = 0.0;
106 double fXPow = 1.0;
107 const double *pn;
108 const double *qn;
110 if ( x < 2.2 )
112 static const double pn22[] = {
113 9.99999992049799098E-1,
114 1.33154163936765307,
115 8.78115804155881782E-1,
116 3.31899559578213215E-1,
117 7.14193832506776067E-2,
118 7.06940843763253131E-3
120 static const double qn22[] = {
121 1.00000000000000000,
122 2.45992070144245533,
123 2.65383972869775752,
124 1.61876655543871376,
125 5.94651311286481502E-1,
126 1.26579413030177940E-1,
127 1.25304936549413393E-2
129 pn = pn22;
130 qn = qn22;
132 else /* if ( x < 6.0 ) this is true, but the compiler does not know */
134 static const double pn60[] = {
135 9.99921140009714409E-1,
136 1.62356584489366647,
137 1.26739901455873222,
138 5.81528574177741135E-1,
139 1.57289620742838702E-1,
140 2.25716982919217555E-2
142 static const double qn60[] = {
143 1.00000000000000000,
144 2.75143870676376208,
145 3.37367334657284535,
146 2.38574194785344389,
147 1.05074004614827206,
148 2.78788439273628983E-1,
149 4.00072964526861362E-2
151 pn = pn60;
152 qn = qn60;
155 for ( unsigned int i = 0; i < 6; ++i )
157 fPSum += pn[i]*fXPow;
158 fQSum += qn[i]*fXPow;
159 fXPow *= x;
161 fQSum += qn[6]*fXPow;
162 fVal = exp( -1.0*x*x )* fPSum / fQSum;
165 /** Approximation algorithm for erfc for 6.0 < x < 26.54 (but used for all
166 x > 6.0). */
167 static void lcl_Erfc2654( double x, double& fVal )
169 static const double pn[] = {
170 5.64189583547756078E-1,
171 8.80253746105525775,
172 3.84683103716117320E1,
173 4.77209965874436377E1,
174 8.08040729052301677
176 static const double qn[] = {
177 1.00000000000000000,
178 1.61020914205869003E1,
179 7.54843505665954743E1,
180 1.12123870801026015E2,
181 3.73997570145040850E1
184 double fPSum = 0.0;
185 double fQSum = 0.0;
186 double fXPow = 1.0;
188 for ( unsigned int i = 0; i <= 4; ++i )
190 fPSum += pn[i]*fXPow;
191 fQSum += qn[i]*fXPow;
192 fXPow /= x*x;
194 fVal = exp(-1.0*x*x)*fPSum / (x*fQSum);
197 namespace {
199 double const nKorrVal[] = {
200 0, 9e-1, 9e-2, 9e-3, 9e-4, 9e-5, 9e-6, 9e-7, 9e-8,
201 9e-9, 9e-10, 9e-11, 9e-12, 9e-13, 9e-14, 9e-15
204 struct StringTraits
206 typedef sal_Char Char;
208 typedef rtl_String String;
210 static inline void createString(rtl_String ** pString,
211 sal_Char const * pChars, sal_Int32 nLen)
213 rtl_string_newFromStr_WithLength(pString, pChars, nLen);
216 static inline void createBuffer(rtl_String ** pBuffer,
217 sal_Int32 * pCapacity)
219 rtl_string_new_WithLength(pBuffer, *pCapacity);
222 static inline void appendChar(rtl_String ** pBuffer, sal_Int32 * pCapacity,
223 sal_Int32 * pOffset, sal_Char cChar)
225 rtl_stringbuffer_insert(pBuffer, pCapacity, *pOffset, &cChar, 1);
226 ++*pOffset;
229 static inline void appendChars(rtl_String ** pBuffer, sal_Int32 * pCapacity,
230 sal_Int32 * pOffset, sal_Char const * pChars,
231 sal_Int32 nLen)
233 rtl_stringbuffer_insert(pBuffer, pCapacity, *pOffset, pChars, nLen);
234 *pOffset += nLen;
237 static inline void appendAscii(rtl_String ** pBuffer, sal_Int32 * pCapacity,
238 sal_Int32 * pOffset, sal_Char const * pStr,
239 sal_Int32 nLen)
241 rtl_stringbuffer_insert(pBuffer, pCapacity, *pOffset, pStr, nLen);
242 *pOffset += nLen;
246 struct UStringTraits
248 typedef sal_Unicode Char;
250 typedef rtl_uString String;
252 static inline void createString(rtl_uString ** pString,
253 sal_Unicode const * pChars, sal_Int32 nLen)
255 rtl_uString_newFromStr_WithLength(pString, pChars, nLen);
258 static inline void createBuffer(rtl_uString ** pBuffer,
259 sal_Int32 * pCapacity)
261 rtl_uString_new_WithLength(pBuffer, *pCapacity);
264 static inline void appendChar(rtl_uString ** pBuffer, sal_Int32 * pCapacity,
265 sal_Int32 * pOffset, sal_Unicode cChar)
267 rtl_uStringbuffer_insert(pBuffer, pCapacity, *pOffset, &cChar, 1);
268 ++*pOffset;
271 static inline void appendChars(rtl_uString ** pBuffer,
272 sal_Int32 * pCapacity, sal_Int32 * pOffset,
273 sal_Unicode const * pChars, sal_Int32 nLen)
275 rtl_uStringbuffer_insert(pBuffer, pCapacity, *pOffset, pChars, nLen);
276 *pOffset += nLen;
279 static inline void appendAscii(rtl_uString ** pBuffer,
280 sal_Int32 * pCapacity, sal_Int32 * pOffset,
281 sal_Char const * pStr, sal_Int32 nLen)
283 rtl_uStringbuffer_insert_ascii(pBuffer, pCapacity, *pOffset, pStr,
284 nLen);
285 *pOffset += nLen;
290 // Solaris C++ 5.2 compiler has problems when "StringT ** pResult" is
291 // "typename T::String ** pResult" instead:
292 template< typename T, typename StringT >
293 inline void doubleToString(StringT ** pResult,
294 sal_Int32 * pResultCapacity, sal_Int32 nResultOffset,
295 double fValue, rtl_math_StringFormat eFormat,
296 sal_Int32 nDecPlaces, typename T::Char cDecSeparator,
297 sal_Int32 const * pGroups,
298 typename T::Char cGroupSeparator,
299 bool bEraseTrailingDecZeros)
301 static double const nRoundVal[] = {
302 5.0e+0, 0.5e+0, 0.5e-1, 0.5e-2, 0.5e-3, 0.5e-4, 0.5e-5, 0.5e-6,
303 0.5e-7, 0.5e-8, 0.5e-9, 0.5e-10,0.5e-11,0.5e-12,0.5e-13,0.5e-14
306 // sign adjustment, instead of testing for fValue<0.0 this will also fetch
307 // -0.0
308 bool bSign = rtl::math::isSignBitSet( fValue );
309 if( bSign )
310 fValue = -fValue;
312 if ( rtl::math::isNan( fValue ) )
314 // #i112652# XMLSchema-2
315 sal_Int32 nCapacity = RTL_CONSTASCII_LENGTH("NaN");
316 if (pResultCapacity == 0)
318 pResultCapacity = &nCapacity;
319 T::createBuffer(pResult, pResultCapacity);
320 nResultOffset = 0;
322 T::appendAscii(pResult, pResultCapacity, &nResultOffset,
323 RTL_CONSTASCII_STRINGPARAM("NaN"));
325 return;
328 bool bHuge = fValue == HUGE_VAL; // g++ 3.0.1 requires it this way...
329 if ( bHuge || rtl::math::isInf( fValue ) )
331 // #i112652# XMLSchema-2
332 sal_Int32 nCapacity = RTL_CONSTASCII_LENGTH("-INF");
333 if (pResultCapacity == 0)
335 pResultCapacity = &nCapacity;
336 T::createBuffer(pResult, pResultCapacity);
337 nResultOffset = 0;
339 if ( bSign )
340 T::appendAscii(pResult, pResultCapacity, &nResultOffset,
341 RTL_CONSTASCII_STRINGPARAM("-"));
342 T::appendAscii(pResult, pResultCapacity, &nResultOffset,
343 RTL_CONSTASCII_STRINGPARAM("INF"));
345 return;
348 // find the exponent
349 int nExp = 0;
350 if ( fValue > 0.0 )
352 nExp = static_cast< int >( floor( log10( fValue ) ) );
353 fValue /= getN10Exp( nExp );
356 switch ( eFormat )
358 case rtl_math_StringFormat_Automatic :
359 { // E or F depending on exponent magnitude
360 int nPrec;
361 if ( nExp <= -15 || nExp >= 15 ) // #58531# was <-16, >16
363 nPrec = 14;
364 eFormat = rtl_math_StringFormat_E;
366 else
368 if ( nExp < 14 )
370 nPrec = 15 - nExp - 1;
371 eFormat = rtl_math_StringFormat_F;
373 else
375 nPrec = 15;
376 eFormat = rtl_math_StringFormat_F;
379 if ( nDecPlaces == rtl_math_DecimalPlaces_Max )
380 nDecPlaces = nPrec;
382 break;
383 case rtl_math_StringFormat_G :
384 { // G-Point, similar to sprintf %G
385 if ( nDecPlaces == rtl_math_DecimalPlaces_DefaultSignificance )
386 nDecPlaces = 6;
387 if ( nExp < -4 || nExp >= nDecPlaces )
389 nDecPlaces = std::max< sal_Int32 >( 1, nDecPlaces - 1 );
390 eFormat = rtl_math_StringFormat_E;
392 else
394 nDecPlaces = std::max< sal_Int32 >( 0, nDecPlaces - nExp - 1 );
395 eFormat = rtl_math_StringFormat_F;
398 break;
399 default:
400 break;
403 sal_Int32 nDigits = nDecPlaces + 1;
405 if( eFormat == rtl_math_StringFormat_F )
406 nDigits += nExp;
408 // Round the number
409 if( nDigits >= 0 )
411 if( ( fValue += nRoundVal[ nDigits > 15 ? 15 : nDigits ] ) >= 10 )
413 fValue = 1.0;
414 nExp++;
415 if( eFormat == rtl_math_StringFormat_F )
416 nDigits++;
420 static sal_Int32 const nBufMax = 256;
421 typename T::Char aBuf[nBufMax];
422 typename T::Char * pBuf;
423 sal_Int32 nBuf = static_cast< sal_Int32 >
424 ( nDigits <= 0 ? std::max< sal_Int32 >( nDecPlaces, abs(nExp) )
425 : nDigits + nDecPlaces ) + 10 + (pGroups ? abs(nDigits) * 2 : 0);
426 if ( nBuf > nBufMax )
428 pBuf = reinterpret_cast< typename T::Char * >(
429 rtl_allocateMemory(nBuf * sizeof (typename T::Char)));
430 OSL_ENSURE(pBuf != 0, "Out of memory");
432 else
433 pBuf = aBuf;
434 typename T::Char * p = pBuf;
435 if ( bSign )
436 *p++ = static_cast< typename T::Char >('-');
438 bool bHasDec = false;
440 int nDecPos;
441 // Check for F format and number < 1
442 if( eFormat == rtl_math_StringFormat_F )
444 if( nExp < 0 )
446 *p++ = static_cast< typename T::Char >('0');
447 if ( nDecPlaces > 0 )
449 *p++ = cDecSeparator;
450 bHasDec = true;
452 sal_Int32 i = ( nDigits <= 0 ? nDecPlaces : -nExp - 1 );
453 while( (i--) > 0 )
454 *p++ = static_cast< typename T::Char >('0');
455 nDecPos = 0;
457 else
458 nDecPos = nExp + 1;
460 else
461 nDecPos = 1;
463 int nGrouping = 0, nGroupSelector = 0, nGroupExceed = 0;
464 if ( nDecPos > 1 && pGroups && pGroups[0] && cGroupSeparator )
466 while ( nGrouping + pGroups[nGroupSelector] < nDecPos )
468 nGrouping += pGroups[ nGroupSelector ];
469 if ( pGroups[nGroupSelector+1] )
471 if ( nGrouping + pGroups[nGroupSelector+1] >= nDecPos )
472 break; // while
473 ++nGroupSelector;
475 else if ( !nGroupExceed )
476 nGroupExceed = nGrouping;
480 // print the number
481 if( nDigits > 0 )
483 for ( int i = 0; ; i++ )
485 if( i < 15 )
487 int nDigit;
488 if (nDigits-1 == 0 && i > 0 && i < 14)
489 nDigit = static_cast< int >( floor( fValue
490 + nKorrVal[15-i] ) );
491 else
492 nDigit = static_cast< int >( fValue + 1E-15 );
493 if (nDigit >= 10)
494 { // after-treatment of up-rounding to the next decade
495 sal_Int32 sLen = static_cast< long >(p-pBuf)-1;
496 if (sLen == -1)
498 p = pBuf;
499 if ( eFormat == rtl_math_StringFormat_F )
501 *p++ = static_cast< typename T::Char >('1');
502 *p++ = static_cast< typename T::Char >('0');
504 else
506 *p++ = static_cast< typename T::Char >('1');
507 *p++ = cDecSeparator;
508 *p++ = static_cast< typename T::Char >('0');
509 nExp++;
510 bHasDec = true;
513 else
515 for (sal_Int32 j = sLen; j >= 0; j--)
517 typename T::Char cS = pBuf[j];
518 if (cS != cDecSeparator)
520 if ( cS != static_cast< typename T::Char >('9'))
522 pBuf[j] = ++cS;
523 j = -1; // break loop
525 else
527 pBuf[j]
528 = static_cast< typename T::Char >('0');
529 if (j == 0)
531 if ( eFormat == rtl_math_StringFormat_F)
532 { // insert '1'
533 typename T::Char * px = p++;
534 while ( pBuf < px )
536 *px = *(px-1);
537 px--;
539 pBuf[0] = static_cast<
540 typename T::Char >('1');
542 else
544 pBuf[j] = static_cast<
545 typename T::Char >('1');
546 nExp++;
552 *p++ = static_cast< typename T::Char >('0');
554 fValue = 0.0;
556 else
558 *p++ = static_cast< typename T::Char >(
559 nDigit + static_cast< typename T::Char >('0') );
560 fValue = ( fValue - nDigit ) * 10.0;
563 else
564 *p++ = static_cast< typename T::Char >('0');
565 if( !--nDigits )
566 break; // for
567 if( nDecPos )
569 if( !--nDecPos )
571 *p++ = cDecSeparator;
572 bHasDec = true;
574 else if ( nDecPos == nGrouping )
576 *p++ = cGroupSeparator;
577 nGrouping -= pGroups[ nGroupSelector ];
578 if ( nGroupSelector && nGrouping < nGroupExceed )
579 --nGroupSelector;
585 if ( !bHasDec && eFormat == rtl_math_StringFormat_F )
586 { // nDecPlaces < 0 did round the value
587 while ( --nDecPos > 0 )
588 { // fill before decimal point
589 if ( nDecPos == nGrouping )
591 *p++ = cGroupSeparator;
592 nGrouping -= pGroups[ nGroupSelector ];
593 if ( nGroupSelector && nGrouping < nGroupExceed )
594 --nGroupSelector;
596 *p++ = static_cast< typename T::Char >('0');
600 if ( bEraseTrailingDecZeros && bHasDec && p > pBuf )
602 while ( *(p-1) == static_cast< typename T::Char >('0') )
603 p--;
604 if ( *(p-1) == cDecSeparator )
605 p--;
608 // Print the exponent ('E', followed by '+' or '-', followed by exactly
609 // three digits). The code in rtl_[u]str_valueOf{Float|Double} relies on
610 // this format.
611 if( eFormat == rtl_math_StringFormat_E )
613 if ( p == pBuf )
614 *p++ = static_cast< typename T::Char >('1');
615 // maybe no nDigits if nDecPlaces < 0
616 *p++ = static_cast< typename T::Char >('E');
617 if( nExp < 0 )
619 nExp = -nExp;
620 *p++ = static_cast< typename T::Char >('-');
622 else
623 *p++ = static_cast< typename T::Char >('+');
624 // if (nExp >= 100 )
625 *p++ = static_cast< typename T::Char >(
626 nExp / 100 + static_cast< typename T::Char >('0') );
627 nExp %= 100;
628 *p++ = static_cast< typename T::Char >(
629 nExp / 10 + static_cast< typename T::Char >('0') );
630 *p++ = static_cast< typename T::Char >(
631 nExp % 10 + static_cast< typename T::Char >('0') );
634 if (pResultCapacity == 0)
635 T::createString(pResult, pBuf, p - pBuf);
636 else
637 T::appendChars(pResult, pResultCapacity, &nResultOffset, pBuf,
638 p - pBuf);
640 if ( pBuf != &aBuf[0] )
641 rtl_freeMemory(pBuf);
646 void SAL_CALL rtl_math_doubleToString(rtl_String ** pResult,
647 sal_Int32 * pResultCapacity,
648 sal_Int32 nResultOffset, double fValue,
649 rtl_math_StringFormat eFormat,
650 sal_Int32 nDecPlaces,
651 sal_Char cDecSeparator,
652 sal_Int32 const * pGroups,
653 sal_Char cGroupSeparator,
654 sal_Bool bEraseTrailingDecZeros)
655 SAL_THROW_EXTERN_C()
657 doubleToString< StringTraits, StringTraits::String >(
658 pResult, pResultCapacity, nResultOffset, fValue, eFormat, nDecPlaces,
659 cDecSeparator, pGroups, cGroupSeparator, bEraseTrailingDecZeros);
662 void SAL_CALL rtl_math_doubleToUString(rtl_uString ** pResult,
663 sal_Int32 * pResultCapacity,
664 sal_Int32 nResultOffset, double fValue,
665 rtl_math_StringFormat eFormat,
666 sal_Int32 nDecPlaces,
667 sal_Unicode cDecSeparator,
668 sal_Int32 const * pGroups,
669 sal_Unicode cGroupSeparator,
670 sal_Bool bEraseTrailingDecZeros)
671 SAL_THROW_EXTERN_C()
673 doubleToString< UStringTraits, UStringTraits::String >(
674 pResult, pResultCapacity, nResultOffset, fValue, eFormat, nDecPlaces,
675 cDecSeparator, pGroups, cGroupSeparator, bEraseTrailingDecZeros);
679 namespace {
681 // if nExp * 10 + nAdd would result in overflow
682 inline bool long10Overflow( long& nExp, int nAdd )
684 if ( nExp > (LONG_MAX/10)
685 || (nExp == (LONG_MAX/10) && nAdd > (LONG_MAX%10)) )
687 nExp = LONG_MAX;
688 return true;
690 return false;
693 template< typename CharT >
694 inline double stringToDouble(CharT const * pBegin, CharT const * pEnd,
695 CharT cDecSeparator, CharT cGroupSeparator,
696 rtl_math_ConversionStatus * pStatus,
697 CharT const ** pParsedEnd)
699 double fVal = 0.0;
700 rtl_math_ConversionStatus eStatus = rtl_math_ConversionStatus_Ok;
702 CharT const * p0 = pBegin;
703 while (p0 != pEnd && (*p0 == CharT(' ') || *p0 == CharT('\t')))
704 ++p0;
705 bool bSign;
706 if (p0 != pEnd && *p0 == CharT('-'))
708 bSign = true;
709 ++p0;
711 else
713 bSign = false;
714 if (p0 != pEnd && *p0 == CharT('+'))
715 ++p0;
717 CharT const * p = p0;
718 bool bDone = false;
720 // #i112652# XMLSchema-2
721 if (3 >= (pEnd - p))
723 if ((CharT('N') == p[0]) && (CharT('a') == p[1])
724 && (CharT('N') == p[2]))
726 p += 3;
727 rtl::math::setNan( &fVal );
728 bDone = true;
730 else if ((CharT('I') == p[0]) && (CharT('N') == p[1])
731 && (CharT('F') == p[2]))
733 p += 3;
734 fVal = HUGE_VAL;
735 eStatus = rtl_math_ConversionStatus_OutOfRange;
736 bDone = true;
740 if (!bDone) // do not recognize e.g. NaN1.23
742 // leading zeros and group separators may be safely ignored
743 while (p != pEnd && (*p == CharT('0') || *p == cGroupSeparator))
744 ++p;
746 long nValExp = 0; // carry along exponent of mantissa
748 // integer part of mantissa
749 for (; p != pEnd; ++p)
751 CharT c = *p;
752 if (rtl::isAsciiDigit(c))
754 fVal = fVal * 10.0 + static_cast< double >( c - CharT('0') );
755 ++nValExp;
757 else if (c != cGroupSeparator)
758 break;
761 // fraction part of mantissa
762 if (p != pEnd && *p == cDecSeparator)
764 ++p;
765 double fFrac = 0.0;
766 long nFracExp = 0;
767 while (p != pEnd && *p == CharT('0'))
769 --nFracExp;
770 ++p;
772 if ( nValExp == 0 )
773 nValExp = nFracExp - 1; // no integer part => fraction exponent
774 // one decimal digit needs ld(10) ~= 3.32 bits
775 static const int nSigs = (DBL_MANT_DIG / 3) + 1;
776 int nDigs = 0;
777 for (; p != pEnd; ++p)
779 CharT c = *p;
780 if (!rtl::isAsciiDigit(c))
781 break;
782 if ( nDigs < nSigs )
783 { // further digits (more than nSigs) don't have any
784 // significance
785 fFrac = fFrac * 10.0 + static_cast<double>(c - CharT('0'));
786 --nFracExp;
787 ++nDigs;
790 if ( fFrac != 0.0 )
791 fVal += rtl::math::pow10Exp( fFrac, nFracExp );
792 else if ( nValExp < 0 )
793 nValExp = 0; // no digit other than 0 after decimal point
796 if ( nValExp > 0 )
797 --nValExp; // started with offset +1 at the first mantissa digit
799 // Exponent
800 if (p != p0 && p != pEnd && (*p == CharT('E') || *p == CharT('e')))
802 CharT const * const pExponent = p;
803 ++p;
804 bool bExpSign;
805 if (p != pEnd && *p == CharT('-'))
807 bExpSign = true;
808 ++p;
810 else
812 bExpSign = false;
813 if (p != pEnd && *p == CharT('+'))
814 ++p;
816 CharT const * const pFirstExpDigit = p;
817 if ( fVal == 0.0 )
818 { // no matter what follows, zero stays zero, but carry on the
819 // offset
820 while (p != pEnd && rtl::isAsciiDigit(*p))
821 ++p;
822 if (p == pFirstExpDigit)
823 { // no digits in exponent, reset end of scan
824 p = pExponent;
827 else
829 bool bOverFlow = false;
830 long nExp = 0;
831 for (; p != pEnd; ++p)
833 CharT c = *p;
834 if (!rtl::isAsciiDigit(c))
835 break;
836 int i = c - CharT('0');
837 if ( long10Overflow( nExp, i ) )
838 bOverFlow = true;
839 else
840 nExp = nExp * 10 + i;
842 if ( nExp )
844 if ( bExpSign )
845 nExp = -nExp;
846 long nAllExp = ( bOverFlow ? 0 : nExp + nValExp );
847 if ( nAllExp > DBL_MAX_10_EXP || (bOverFlow && !bExpSign) )
848 { // overflow
849 fVal = HUGE_VAL;
850 eStatus = rtl_math_ConversionStatus_OutOfRange;
852 else if ((nAllExp < DBL_MIN_10_EXP) ||
853 (bOverFlow && bExpSign) )
854 { // underflow
855 fVal = 0.0;
856 eStatus = rtl_math_ConversionStatus_OutOfRange;
858 else if ( nExp > DBL_MAX_10_EXP || nExp < DBL_MIN_10_EXP )
859 { // compensate exponents
860 fVal = rtl::math::pow10Exp( fVal, -nValExp );
861 fVal = rtl::math::pow10Exp( fVal, nAllExp );
863 else
864 fVal = rtl::math::pow10Exp( fVal, nExp ); // normal
866 else if (p == pFirstExpDigit)
867 { // no digits in exponent, reset end of scan
868 p = pExponent;
872 else if (p - p0 == 2 && p != pEnd && p[0] == CharT('#')
873 && p[-1] == cDecSeparator && p[-2] == CharT('1'))
875 if (pEnd - p >= 4 && p[1] == CharT('I') && p[2] == CharT('N')
876 && p[3] == CharT('F'))
878 // "1.#INF", "+1.#INF", "-1.#INF"
879 p += 4;
880 fVal = HUGE_VAL;
881 eStatus = rtl_math_ConversionStatus_OutOfRange;
882 // Eat any further digits:
883 while (p != pEnd && rtl::isAsciiDigit(*p))
884 ++p;
886 else if (pEnd - p >= 4 && p[1] == CharT('N') && p[2] == CharT('A')
887 && p[3] == CharT('N'))
889 // "1.#NAN", "+1.#NAN", "-1.#NAN"
890 p += 4;
891 rtl::math::setNan( &fVal );
892 if (bSign)
894 union {
895 double sd;
896 sal_math_Double md;
897 } m;
898 m.sd = fVal;
899 m.md.w32_parts.msw |= 0x80000000; // create negative NaN
900 fVal = m.sd;
901 bSign = false; // don't negate again
903 // Eat any further digits:
904 while (p != pEnd && rtl::isAsciiDigit(*p))
905 ++p;
910 // overflow also if more than DBL_MAX_10_EXP digits without decimal
911 // separator, or 0. and more than DBL_MIN_10_EXP digits, ...
912 bool bHuge = fVal == HUGE_VAL; // g++ 3.0.1 requires it this way...
913 if ( bHuge )
914 eStatus = rtl_math_ConversionStatus_OutOfRange;
916 if ( bSign )
917 fVal = -fVal;
919 if (pStatus != 0)
920 *pStatus = eStatus;
921 if (pParsedEnd != 0)
922 *pParsedEnd = p == p0 ? pBegin : p;
924 return fVal;
929 double SAL_CALL rtl_math_stringToDouble(sal_Char const * pBegin,
930 sal_Char const * pEnd,
931 sal_Char cDecSeparator,
932 sal_Char cGroupSeparator,
933 rtl_math_ConversionStatus * pStatus,
934 sal_Char const ** pParsedEnd)
935 SAL_THROW_EXTERN_C()
937 return stringToDouble(pBegin, pEnd, cDecSeparator, cGroupSeparator, pStatus,
938 pParsedEnd);
941 double SAL_CALL rtl_math_uStringToDouble(sal_Unicode const * pBegin,
942 sal_Unicode const * pEnd,
943 sal_Unicode cDecSeparator,
944 sal_Unicode cGroupSeparator,
945 rtl_math_ConversionStatus * pStatus,
946 sal_Unicode const ** pParsedEnd)
947 SAL_THROW_EXTERN_C()
949 return stringToDouble(pBegin, pEnd, cDecSeparator, cGroupSeparator, pStatus,
950 pParsedEnd);
953 double SAL_CALL rtl_math_round(double fValue, int nDecPlaces,
954 enum rtl_math_RoundingMode eMode)
955 SAL_THROW_EXTERN_C()
957 OSL_ASSERT(nDecPlaces >= -20 && nDecPlaces <= 20);
959 if ( fValue == 0.0 )
960 return fValue;
962 // sign adjustment
963 bool bSign = rtl::math::isSignBitSet( fValue );
964 if ( bSign )
965 fValue = -fValue;
967 double fFac = 0;
968 if ( nDecPlaces != 0 )
970 // max 20 decimals, we don't have unlimited precision
971 // #38810# and no overflow on fValue*=fFac
972 if ( nDecPlaces < -20 || 20 < nDecPlaces || fValue > (DBL_MAX / 1e20) )
973 return bSign ? -fValue : fValue;
975 fFac = getN10Exp( nDecPlaces );
976 fValue *= fFac;
978 //else //! uninitialized fFac, not needed
980 switch ( eMode )
982 case rtl_math_RoundingMode_Corrected :
984 int nExp; // exponent for correction
985 if ( fValue > 0.0 )
986 nExp = static_cast<int>( floor( log10( fValue ) ) );
987 else
988 nExp = 0;
989 int nIndex = 15 - nExp;
990 if ( nIndex > 15 )
991 nIndex = 15;
992 else if ( nIndex <= 1 )
993 nIndex = 0;
994 fValue = floor( fValue + 0.5 + nKorrVal[nIndex] );
996 break;
997 case rtl_math_RoundingMode_Down :
998 fValue = rtl::math::approxFloor( fValue );
999 break;
1000 case rtl_math_RoundingMode_Up :
1001 fValue = rtl::math::approxCeil( fValue );
1002 break;
1003 case rtl_math_RoundingMode_Floor :
1004 fValue = bSign ? rtl::math::approxCeil( fValue )
1005 : rtl::math::approxFloor( fValue );
1006 break;
1007 case rtl_math_RoundingMode_Ceiling :
1008 fValue = bSign ? rtl::math::approxFloor( fValue )
1009 : rtl::math::approxCeil( fValue );
1010 break;
1011 case rtl_math_RoundingMode_HalfDown :
1013 double f = floor( fValue );
1014 fValue = ((fValue - f) <= 0.5) ? f : ceil( fValue );
1016 break;
1017 case rtl_math_RoundingMode_HalfUp :
1019 double f = floor( fValue );
1020 fValue = ((fValue - f) < 0.5) ? f : ceil( fValue );
1022 break;
1023 case rtl_math_RoundingMode_HalfEven :
1024 #if defined FLT_ROUNDS
1026 Use fast version. FLT_ROUNDS may be defined to a function by some compilers!
1028 DBL_EPSILON is the smallest fractional number which can be represented,
1029 its reciprocal is therefore the smallest number that cannot have a
1030 fractional part. Once you add this reciprocal to `x', its fractional part
1031 is stripped off. Simply subtracting the reciprocal back out returns `x'
1032 without its fractional component.
1033 Simple, clever, and elegant - thanks to Ross Cottrell, the original author,
1034 who placed it into public domain.
1036 volatile: prevent compiler from being too smart
1038 if ( FLT_ROUNDS == 1 )
1040 volatile double x = fValue + 1.0 / DBL_EPSILON;
1041 fValue = x - 1.0 / DBL_EPSILON;
1043 else
1044 #endif // FLT_ROUNDS
1046 double f = floor( fValue );
1047 if ( (fValue - f) != 0.5 )
1048 fValue = floor( fValue + 0.5 );
1049 else
1051 double g = f / 2.0;
1052 fValue = (g == floor( g )) ? f : (f + 1.0);
1055 break;
1056 default:
1057 OSL_ASSERT(false);
1058 break;
1061 if ( nDecPlaces != 0 )
1062 fValue /= fFac;
1064 return bSign ? -fValue : fValue;
1068 double SAL_CALL rtl_math_pow10Exp(double fValue, int nExp) SAL_THROW_EXTERN_C()
1070 return fValue * getN10Exp( nExp );
1074 double SAL_CALL rtl_math_approxValue( double fValue ) SAL_THROW_EXTERN_C()
1076 if (fValue == 0.0 || fValue == HUGE_VAL || !::rtl::math::isFinite( fValue))
1077 // We don't handle these conditions. Bail out.
1078 return fValue;
1080 double fOrigValue = fValue;
1082 bool bSign = ::rtl::math::isSignBitSet( fValue);
1083 if (bSign)
1084 fValue = -fValue;
1086 int nExp = static_cast<int>( floor( log10( fValue)));
1087 nExp = 14 - nExp;
1088 double fExpValue = getN10Exp( nExp);
1090 fValue *= fExpValue;
1091 // If the original value was near DBL_MIN we got an overflow. Restore and
1092 // bail out.
1093 if (!rtl::math::isFinite( fValue))
1094 return fOrigValue;
1095 fValue = rtl_math_round( fValue, 0, rtl_math_RoundingMode_Corrected);
1096 fValue /= fExpValue;
1097 // If the original value was near DBL_MAX we got an overflow. Restore and
1098 // bail out.
1099 if (!rtl::math::isFinite( fValue))
1100 return fOrigValue;
1102 return bSign ? -fValue : fValue;
1106 double SAL_CALL rtl_math_expm1( double fValue ) SAL_THROW_EXTERN_C()
1108 double fe = exp( fValue );
1109 if (fe == 1.0)
1110 return fValue;
1111 if (fe-1.0 == -1.0)
1112 return -1.0;
1113 return (fe-1.0) * fValue / log(fe);
1117 double SAL_CALL rtl_math_log1p( double fValue ) SAL_THROW_EXTERN_C()
1119 // Use volatile because a compiler may be too smart "optimizing" the
1120 // condition such that in certain cases the else path was called even if
1121 // (fp==1.0) was true, where the term (fp-1.0) then resulted in 0.0 and
1122 // hence the entire expression resulted in NaN.
1123 // Happened with g++ 3.4.1 and an input value of 9.87E-18
1124 volatile double fp = 1.0 + fValue;
1125 if (fp == 1.0)
1126 return fValue;
1127 else
1128 return log(fp) * fValue / (fp-1.0);
1132 double SAL_CALL rtl_math_atanh( double fValue ) SAL_THROW_EXTERN_C()
1134 return 0.5 * rtl_math_log1p( 2.0 * fValue / (1.0-fValue) );
1138 /** Parent error function (erf) that calls different algorithms based on the
1139 value of x. It takes care of cases where x is negative as erf is an odd
1140 function i.e. erf(-x) = -erf(x).
1142 Kramer, W., and Blomquist, F., 2000, Algorithms with Guaranteed Error Bounds
1143 for the Error Function and the Complementary Error Function
1145 http://www.math.uni-wuppertal.de/wrswt/literatur_en.html
1147 @author Kohei Yoshida <kohei@openoffice.org>
1149 @see #i55735#
1151 double SAL_CALL rtl_math_erf( double x ) SAL_THROW_EXTERN_C()
1153 if( x == 0.0 )
1154 return 0.0;
1156 bool bNegative = false;
1157 if ( x < 0.0 )
1159 x = fabs( x );
1160 bNegative = true;
1163 double fErf = 1.0;
1164 if ( x < 1.0e-10 )
1165 fErf = (double) (x*1.1283791670955125738961589031215452L);
1166 else if ( x < 0.65 )
1167 lcl_Erf0065( x, fErf );
1168 else
1169 fErf = 1.0 - rtl_math_erfc( x );
1171 if ( bNegative )
1172 fErf *= -1.0;
1174 return fErf;
1178 /** Parent complementary error function (erfc) that calls different algorithms
1179 based on the value of x. It takes care of cases where x is negative as erfc
1180 satisfies relationship erfc(-x) = 2 - erfc(x). See the comment for Erf(x)
1181 for the source publication.
1183 @author Kohei Yoshida <kohei@openoffice.org>
1185 @see #i55735#, moved from module scaddins (#i97091#)
1188 double SAL_CALL rtl_math_erfc( double x ) SAL_THROW_EXTERN_C()
1190 if ( x == 0.0 )
1191 return 1.0;
1193 bool bNegative = false;
1194 if ( x < 0.0 )
1196 x = fabs( x );
1197 bNegative = true;
1200 double fErfc = 0.0;
1201 if ( x >= 0.65 )
1203 if ( x < 6.0 )
1204 lcl_Erfc0600( x, fErfc );
1205 else
1206 lcl_Erfc2654( x, fErfc );
1208 else
1209 fErfc = 1.0 - rtl_math_erf( x );
1211 if ( bNegative )
1212 fErfc = 2.0 - fErfc;
1214 return fErfc;
1217 /** improved accuracy of asinh for |x| large and for x near zero
1218 @see #i97605#
1220 double SAL_CALL rtl_math_asinh( double fX ) SAL_THROW_EXTERN_C()
1222 if ( fX == 0.0 )
1223 return 0.0;
1224 else
1226 double fSign = 1.0;
1227 if ( fX < 0.0 )
1229 fX = - fX;
1230 fSign = -1.0;
1232 if ( fX < 0.125 )
1233 return fSign * rtl_math_log1p( fX + fX*fX / (1.0 + sqrt( 1.0 + fX*fX)));
1234 else if ( fX < 1.25e7 )
1235 return fSign * log( fX + sqrt( 1.0 + fX*fX));
1236 else
1237 return fSign * log( 2.0*fX);
1241 /** improved accuracy of acosh for x large and for x near 1
1242 @see #i97605#
1244 double SAL_CALL rtl_math_acosh( double fX ) SAL_THROW_EXTERN_C()
1246 volatile double fZ = fX - 1.0;
1247 if ( fX < 1.0 )
1249 double fResult;
1250 ::rtl::math::setNan( &fResult );
1251 return fResult;
1253 else if ( fX == 1.0 )
1254 return 0.0;
1255 else if ( fX < 1.1 )
1256 return rtl_math_log1p( fZ + sqrt( fZ*fZ + 2.0*fZ));
1257 else if ( fX < 1.25e7 )
1258 return log( fX + sqrt( fX*fX - 1.0));
1259 else
1260 return log( 2.0*fX);
1263 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */