You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1624 lines
52 KiB

36 years ago
30 years ago
36 years ago
30 years ago
36 years ago
36 years ago
30 years ago
36 years ago
36 years ago
36 years ago
36 years ago
18 years ago
18 years ago
18 years ago
18 years ago
19 years ago
30 years ago
30 years ago
30 years ago
36 years ago
30 years ago
36 years ago
36 years ago
36 years ago
  1. /* Math module -- standard C math library functions, pi and e */
  2. /* Here are some comments from Tim Peters, extracted from the
  3. discussion attached to http://bugs.python.org/issue1640. They
  4. describe the general aims of the math module with respect to
  5. special values, IEEE-754 floating-point exceptions, and Python
  6. exceptions.
  7. These are the "spirit of 754" rules:
  8. 1. If the mathematical result is a real number, but of magnitude too
  9. large to approximate by a machine float, overflow is signaled and the
  10. result is an infinity (with the appropriate sign).
  11. 2. If the mathematical result is a real number, but of magnitude too
  12. small to approximate by a machine float, underflow is signaled and the
  13. result is a zero (with the appropriate sign).
  14. 3. At a singularity (a value x such that the limit of f(y) as y
  15. approaches x exists and is an infinity), "divide by zero" is signaled
  16. and the result is an infinity (with the appropriate sign). This is
  17. complicated a little by that the left-side and right-side limits may
  18. not be the same; e.g., 1/x approaches +inf or -inf as x approaches 0
  19. from the positive or negative directions. In that specific case, the
  20. sign of the zero determines the result of 1/0.
  21. 4. At a point where a function has no defined result in the extended
  22. reals (i.e., the reals plus an infinity or two), invalid operation is
  23. signaled and a NaN is returned.
  24. And these are what Python has historically /tried/ to do (but not
  25. always successfully, as platform libm behavior varies a lot):
  26. For #1, raise OverflowError.
  27. For #2, return a zero (with the appropriate sign if that happens by
  28. accident ;-)).
  29. For #3 and #4, raise ValueError. It may have made sense to raise
  30. Python's ZeroDivisionError in #3, but historically that's only been
  31. raised for division by zero and mod by zero.
  32. */
  33. /*
  34. In general, on an IEEE-754 platform the aim is to follow the C99
  35. standard, including Annex 'F', whenever possible. Where the
  36. standard recommends raising the 'divide-by-zero' or 'invalid'
  37. floating-point exceptions, Python should raise a ValueError. Where
  38. the standard recommends raising 'overflow', Python should raise an
  39. OverflowError. In all other circumstances a value should be
  40. returned.
  41. */
  42. #include "Python.h"
  43. #include "_math.h"
  44. #ifdef _OSF_SOURCE
  45. /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
  46. extern double copysign(double, double);
  47. #endif
  48. /*
  49. sin(pi*x), giving accurate results for all finite x (especially x
  50. integral or close to an integer). This is here for use in the
  51. reflection formula for the gamma function. It conforms to IEEE
  52. 754-2008 for finite arguments, but not for infinities or nans.
  53. */
  54. static const double pi = 3.141592653589793238462643383279502884197;
  55. static const double sqrtpi = 1.772453850905516027298167483341145182798;
  56. static double
  57. sinpi(double x)
  58. {
  59. double y, r;
  60. int n;
  61. /* this function should only ever be called for finite arguments */
  62. assert(Py_IS_FINITE(x));
  63. y = fmod(fabs(x), 2.0);
  64. n = (int)round(2.0*y);
  65. assert(0 <= n && n <= 4);
  66. switch (n) {
  67. case 0:
  68. r = sin(pi*y);
  69. break;
  70. case 1:
  71. r = cos(pi*(y-0.5));
  72. break;
  73. case 2:
  74. /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
  75. -0.0 instead of 0.0 when y == 1.0. */
  76. r = sin(pi*(1.0-y));
  77. break;
  78. case 3:
  79. r = -cos(pi*(y-1.5));
  80. break;
  81. case 4:
  82. r = sin(pi*(y-2.0));
  83. break;
  84. default:
  85. assert(0); /* should never get here */
  86. r = -1.23e200; /* silence gcc warning */
  87. }
  88. return copysign(1.0, x)*r;
  89. }
  90. /* Implementation of the real gamma function. In extensive but non-exhaustive
  91. random tests, this function proved accurate to within <= 10 ulps across the
  92. entire float domain. Note that accuracy may depend on the quality of the
  93. system math functions, the pow function in particular. Special cases
  94. follow C99 annex F. The parameters and method are tailored to platforms
  95. whose double format is the IEEE 754 binary64 format.
  96. Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
  97. and g=6.024680040776729583740234375; these parameters are amongst those
  98. used by the Boost library. Following Boost (again), we re-express the
  99. Lanczos sum as a rational function, and compute it that way. The
  100. coefficients below were computed independently using MPFR, and have been
  101. double-checked against the coefficients in the Boost source code.
  102. For x < 0.0 we use the reflection formula.
  103. There's one minor tweak that deserves explanation: Lanczos' formula for
  104. Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
  105. values, x+g-0.5 can be represented exactly. However, in cases where it
  106. can't be represented exactly the small error in x+g-0.5 can be magnified
  107. significantly by the pow and exp calls, especially for large x. A cheap
  108. correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
  109. involved in the computation of x+g-0.5 (that is, e = computed value of
  110. x+g-0.5 - exact value of x+g-0.5). Here's the proof:
  111. Correction factor
  112. -----------------
  113. Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
  114. double, and e is tiny. Then:
  115. pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
  116. = pow(y, x-0.5)/exp(y) * C,
  117. where the correction_factor C is given by
  118. C = pow(1-e/y, x-0.5) * exp(e)
  119. Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
  120. C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
  121. But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
  122. pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
  123. Note that for accuracy, when computing r*C it's better to do
  124. r + e*g/y*r;
  125. than
  126. r * (1 + e*g/y);
  127. since the addition in the latter throws away most of the bits of
  128. information in e*g/y.
  129. */
  130. #define LANCZOS_N 13
  131. static const double lanczos_g = 6.024680040776729583740234375;
  132. static const double lanczos_g_minus_half = 5.524680040776729583740234375;
  133. static const double lanczos_num_coeffs[LANCZOS_N] = {
  134. 23531376880.410759688572007674451636754734846804940,
  135. 42919803642.649098768957899047001988850926355848959,
  136. 35711959237.355668049440185451547166705960488635843,
  137. 17921034426.037209699919755754458931112671403265390,
  138. 6039542586.3520280050642916443072979210699388420708,
  139. 1439720407.3117216736632230727949123939715485786772,
  140. 248874557.86205415651146038641322942321632125127801,
  141. 31426415.585400194380614231628318205362874684987640,
  142. 2876370.6289353724412254090516208496135991145378768,
  143. 186056.26539522349504029498971604569928220784236328,
  144. 8071.6720023658162106380029022722506138218516325024,
  145. 210.82427775157934587250973392071336271166969580291,
  146. 2.5066282746310002701649081771338373386264310793408
  147. };
  148. /* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
  149. static const double lanczos_den_coeffs[LANCZOS_N] = {
  150. 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
  151. 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
  152. /* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
  153. #define NGAMMA_INTEGRAL 23
  154. static const double gamma_integral[NGAMMA_INTEGRAL] = {
  155. 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
  156. 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
  157. 1307674368000.0, 20922789888000.0, 355687428096000.0,
  158. 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
  159. 51090942171709440000.0, 1124000727777607680000.0,
  160. };
  161. /* Lanczos' sum L_g(x), for positive x */
  162. static double
  163. lanczos_sum(double x)
  164. {
  165. double num = 0.0, den = 0.0;
  166. int i;
  167. assert(x > 0.0);
  168. /* evaluate the rational function lanczos_sum(x). For large
  169. x, the obvious algorithm risks overflow, so we instead
  170. rescale the denominator and numerator of the rational
  171. function by x**(1-LANCZOS_N) and treat this as a
  172. rational function in 1/x. This also reduces the error for
  173. larger x values. The choice of cutoff point (5.0 below) is
  174. somewhat arbitrary; in tests, smaller cutoff values than
  175. this resulted in lower accuracy. */
  176. if (x < 5.0) {
  177. for (i = LANCZOS_N; --i >= 0; ) {
  178. num = num * x + lanczos_num_coeffs[i];
  179. den = den * x + lanczos_den_coeffs[i];
  180. }
  181. }
  182. else {
  183. for (i = 0; i < LANCZOS_N; i++) {
  184. num = num / x + lanczos_num_coeffs[i];
  185. den = den / x + lanczos_den_coeffs[i];
  186. }
  187. }
  188. return num/den;
  189. }
  190. static double
  191. m_tgamma(double x)
  192. {
  193. double absx, r, y, z, sqrtpow;
  194. /* special cases */
  195. if (!Py_IS_FINITE(x)) {
  196. if (Py_IS_NAN(x) || x > 0.0)
  197. return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
  198. else {
  199. errno = EDOM;
  200. return Py_NAN; /* tgamma(-inf) = nan, invalid */
  201. }
  202. }
  203. if (x == 0.0) {
  204. errno = EDOM;
  205. return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */
  206. }
  207. /* integer arguments */
  208. if (x == floor(x)) {
  209. if (x < 0.0) {
  210. errno = EDOM; /* tgamma(n) = nan, invalid for */
  211. return Py_NAN; /* negative integers n */
  212. }
  213. if (x <= NGAMMA_INTEGRAL)
  214. return gamma_integral[(int)x - 1];
  215. }
  216. absx = fabs(x);
  217. /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
  218. if (absx < 1e-20) {
  219. r = 1.0/x;
  220. if (Py_IS_INFINITY(r))
  221. errno = ERANGE;
  222. return r;
  223. }
  224. /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
  225. x > 200, and underflows to +-0.0 for x < -200, not a negative
  226. integer. */
  227. if (absx > 200.0) {
  228. if (x < 0.0) {
  229. return 0.0/sinpi(x);
  230. }
  231. else {
  232. errno = ERANGE;
  233. return Py_HUGE_VAL;
  234. }
  235. }
  236. y = absx + lanczos_g_minus_half;
  237. /* compute error in sum */
  238. if (absx > lanczos_g_minus_half) {
  239. /* note: the correction can be foiled by an optimizing
  240. compiler that (incorrectly) thinks that an expression like
  241. a + b - a - b can be optimized to 0.0. This shouldn't
  242. happen in a standards-conforming compiler. */
  243. double q = y - absx;
  244. z = q - lanczos_g_minus_half;
  245. }
  246. else {
  247. double q = y - lanczos_g_minus_half;
  248. z = q - absx;
  249. }
  250. z = z * lanczos_g / y;
  251. if (x < 0.0) {
  252. r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
  253. r -= z * r;
  254. if (absx < 140.0) {
  255. r /= pow(y, absx - 0.5);
  256. }
  257. else {
  258. sqrtpow = pow(y, absx / 2.0 - 0.25);
  259. r /= sqrtpow;
  260. r /= sqrtpow;
  261. }
  262. }
  263. else {
  264. r = lanczos_sum(absx) / exp(y);
  265. r += z * r;
  266. if (absx < 140.0) {
  267. r *= pow(y, absx - 0.5);
  268. }
  269. else {
  270. sqrtpow = pow(y, absx / 2.0 - 0.25);
  271. r *= sqrtpow;
  272. r *= sqrtpow;
  273. }
  274. }
  275. if (Py_IS_INFINITY(r))
  276. errno = ERANGE;
  277. return r;
  278. }
  279. /*
  280. lgamma: natural log of the absolute value of the Gamma function.
  281. For large arguments, Lanczos' formula works extremely well here.
  282. */
  283. static double
  284. m_lgamma(double x)
  285. {
  286. double r, absx;
  287. /* special cases */
  288. if (!Py_IS_FINITE(x)) {
  289. if (Py_IS_NAN(x))
  290. return x; /* lgamma(nan) = nan */
  291. else
  292. return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
  293. }
  294. /* integer arguments */
  295. if (x == floor(x) && x <= 2.0) {
  296. if (x <= 0.0) {
  297. errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
  298. return Py_HUGE_VAL; /* integers n <= 0 */
  299. }
  300. else {
  301. return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
  302. }
  303. }
  304. absx = fabs(x);
  305. /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
  306. if (absx < 1e-20)
  307. return -log(absx);
  308. /* Lanczos' formula */
  309. if (x > 0.0) {
  310. /* we could save a fraction of a ulp in accuracy by having a
  311. second set of numerator coefficients for lanczos_sum that
  312. absorbed the exp(-lanczos_g) term, and throwing out the
  313. lanczos_g subtraction below; it's probably not worth it. */
  314. r = log(lanczos_sum(x)) - lanczos_g +
  315. (x-0.5)*(log(x+lanczos_g-0.5)-1);
  316. }
  317. else {
  318. r = log(pi) - log(fabs(sinpi(absx))) - log(absx) -
  319. (log(lanczos_sum(absx)) - lanczos_g +
  320. (absx-0.5)*(log(absx+lanczos_g-0.5)-1));
  321. }
  322. if (Py_IS_INFINITY(r))
  323. errno = ERANGE;
  324. return r;
  325. }
  326. /*
  327. Implementations of the error function erf(x) and the complementary error
  328. function erfc(x).
  329. Method: following 'Numerical Recipes' by Flannery, Press et. al. (2nd ed.,
  330. Cambridge University Press), we use a series approximation for erf for
  331. small x, and a continued fraction approximation for erfc(x) for larger x;
  332. combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
  333. this gives us erf(x) and erfc(x) for all x.
  334. The series expansion used is:
  335. erf(x) = x*exp(-x*x)/sqrt(pi) * [
  336. 2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
  337. The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
  338. This series converges well for smallish x, but slowly for larger x.
  339. The continued fraction expansion used is:
  340. erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
  341. 3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
  342. after the first term, the general term has the form:
  343. k*(k-0.5)/(2*k+0.5 + x**2 - ...).
  344. This expansion converges fast for larger x, but convergence becomes
  345. infinitely slow as x approaches 0.0. The (somewhat naive) continued
  346. fraction evaluation algorithm used below also risks overflow for large x;
  347. but for large x, erfc(x) == 0.0 to within machine precision. (For
  348. example, erfc(30.0) is approximately 2.56e-393).
  349. Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
  350. continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
  351. ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
  352. numbers of terms to use for the relevant expansions. */
  353. #define ERF_SERIES_CUTOFF 1.5
  354. #define ERF_SERIES_TERMS 25
  355. #define ERFC_CONTFRAC_CUTOFF 30.0
  356. #define ERFC_CONTFRAC_TERMS 50
  357. /*
  358. Error function, via power series.
  359. Given a finite float x, return an approximation to erf(x).
  360. Converges reasonably fast for small x.
  361. */
  362. static double
  363. m_erf_series(double x)
  364. {
  365. double x2, acc, fk, result;
  366. int i, saved_errno;
  367. x2 = x * x;
  368. acc = 0.0;
  369. fk = (double)ERF_SERIES_TERMS + 0.5;
  370. for (i = 0; i < ERF_SERIES_TERMS; i++) {
  371. acc = 2.0 + x2 * acc / fk;
  372. fk -= 1.0;
  373. }
  374. /* Make sure the exp call doesn't affect errno;
  375. see m_erfc_contfrac for more. */
  376. saved_errno = errno;
  377. result = acc * x * exp(-x2) / sqrtpi;
  378. errno = saved_errno;
  379. return result;
  380. }
  381. /*
  382. Complementary error function, via continued fraction expansion.
  383. Given a positive float x, return an approximation to erfc(x). Converges
  384. reasonably fast for x large (say, x > 2.0), and should be safe from
  385. overflow if x and nterms are not too large. On an IEEE 754 machine, with x
  386. <= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
  387. than the smallest representable nonzero float. */
  388. static double
  389. m_erfc_contfrac(double x)
  390. {
  391. double x2, a, da, p, p_last, q, q_last, b, result;
  392. int i, saved_errno;
  393. if (x >= ERFC_CONTFRAC_CUTOFF)
  394. return 0.0;
  395. x2 = x*x;
  396. a = 0.0;
  397. da = 0.5;
  398. p = 1.0; p_last = 0.0;
  399. q = da + x2; q_last = 1.0;
  400. for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
  401. double temp;
  402. a += da;
  403. da += 2.0;
  404. b = da + x2;
  405. temp = p; p = b*p - a*p_last; p_last = temp;
  406. temp = q; q = b*q - a*q_last; q_last = temp;
  407. }
  408. /* Issue #8986: On some platforms, exp sets errno on underflow to zero;
  409. save the current errno value so that we can restore it later. */
  410. saved_errno = errno;
  411. result = p / q * x * exp(-x2) / sqrtpi;
  412. errno = saved_errno;
  413. return result;
  414. }
  415. /* Error function erf(x), for general x */
  416. static double
  417. m_erf(double x)
  418. {
  419. double absx, cf;
  420. if (Py_IS_NAN(x))
  421. return x;
  422. absx = fabs(x);
  423. if (absx < ERF_SERIES_CUTOFF)
  424. return m_erf_series(x);
  425. else {
  426. cf = m_erfc_contfrac(absx);
  427. return x > 0.0 ? 1.0 - cf : cf - 1.0;
  428. }
  429. }
  430. /* Complementary error function erfc(x), for general x. */
  431. static double
  432. m_erfc(double x)
  433. {
  434. double absx, cf;
  435. if (Py_IS_NAN(x))
  436. return x;
  437. absx = fabs(x);
  438. if (absx < ERF_SERIES_CUTOFF)
  439. return 1.0 - m_erf_series(x);
  440. else {
  441. cf = m_erfc_contfrac(absx);
  442. return x > 0.0 ? cf : 2.0 - cf;
  443. }
  444. }
  445. /*
  446. wrapper for atan2 that deals directly with special cases before
  447. delegating to the platform libm for the remaining cases. This
  448. is necessary to get consistent behaviour across platforms.
  449. Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
  450. always follow C99.
  451. */
  452. static double
  453. m_atan2(double y, double x)
  454. {
  455. if (Py_IS_NAN(x) || Py_IS_NAN(y))
  456. return Py_NAN;
  457. if (Py_IS_INFINITY(y)) {
  458. if (Py_IS_INFINITY(x)) {
  459. if (copysign(1., x) == 1.)
  460. /* atan2(+-inf, +inf) == +-pi/4 */
  461. return copysign(0.25*Py_MATH_PI, y);
  462. else
  463. /* atan2(+-inf, -inf) == +-pi*3/4 */
  464. return copysign(0.75*Py_MATH_PI, y);
  465. }
  466. /* atan2(+-inf, x) == +-pi/2 for finite x */
  467. return copysign(0.5*Py_MATH_PI, y);
  468. }
  469. if (Py_IS_INFINITY(x) || y == 0.) {
  470. if (copysign(1., x) == 1.)
  471. /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
  472. return copysign(0., y);
  473. else
  474. /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
  475. return copysign(Py_MATH_PI, y);
  476. }
  477. return atan2(y, x);
  478. }
  479. /*
  480. Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
  481. log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
  482. special values directly, passing positive non-special values through to
  483. the system log/log10.
  484. */
  485. static double
  486. m_log(double x)
  487. {
  488. if (Py_IS_FINITE(x)) {
  489. if (x > 0.0)
  490. return log(x);
  491. errno = EDOM;
  492. if (x == 0.0)
  493. return -Py_HUGE_VAL; /* log(0) = -inf */
  494. else
  495. return Py_NAN; /* log(-ve) = nan */
  496. }
  497. else if (Py_IS_NAN(x))
  498. return x; /* log(nan) = nan */
  499. else if (x > 0.0)
  500. return x; /* log(inf) = inf */
  501. else {
  502. errno = EDOM;
  503. return Py_NAN; /* log(-inf) = nan */
  504. }
  505. }
  506. static double
  507. m_log10(double x)
  508. {
  509. if (Py_IS_FINITE(x)) {
  510. if (x > 0.0)
  511. return log10(x);
  512. errno = EDOM;
  513. if (x == 0.0)
  514. return -Py_HUGE_VAL; /* log10(0) = -inf */
  515. else
  516. return Py_NAN; /* log10(-ve) = nan */
  517. }
  518. else if (Py_IS_NAN(x))
  519. return x; /* log10(nan) = nan */
  520. else if (x > 0.0)
  521. return x; /* log10(inf) = inf */
  522. else {
  523. errno = EDOM;
  524. return Py_NAN; /* log10(-inf) = nan */
  525. }
  526. }
  527. /* Call is_error when errno != 0, and where x is the result libm
  528. * returned. is_error will usually set up an exception and return
  529. * true (1), but may return false (0) without setting up an exception.
  530. */
  531. static int
  532. is_error(double x)
  533. {
  534. int result = 1; /* presumption of guilt */
  535. assert(errno); /* non-zero errno is a precondition for calling */
  536. if (errno == EDOM)
  537. PyErr_SetString(PyExc_ValueError, "math domain error");
  538. else if (errno == ERANGE) {
  539. /* ANSI C generally requires libm functions to set ERANGE
  540. * on overflow, but also generally *allows* them to set
  541. * ERANGE on underflow too. There's no consistency about
  542. * the latter across platforms.
  543. * Alas, C99 never requires that errno be set.
  544. * Here we suppress the underflow errors (libm functions
  545. * should return a zero on underflow, and +- HUGE_VAL on
  546. * overflow, so testing the result for zero suffices to
  547. * distinguish the cases).
  548. *
  549. * On some platforms (Ubuntu/ia64) it seems that errno can be
  550. * set to ERANGE for subnormal results that do *not* underflow
  551. * to zero. So to be safe, we'll ignore ERANGE whenever the
  552. * function result is less than one in absolute value.
  553. */
  554. if (fabs(x) < 1.0)
  555. result = 0;
  556. else
  557. PyErr_SetString(PyExc_OverflowError,
  558. "math range error");
  559. }
  560. else
  561. /* Unexpected math error */
  562. PyErr_SetFromErrno(PyExc_ValueError);
  563. return result;
  564. }
  565. /*
  566. math_1 is used to wrap a libm function f that takes a double
  567. arguments and returns a double.
  568. The error reporting follows these rules, which are designed to do
  569. the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
  570. platforms.
  571. - a NaN result from non-NaN inputs causes ValueError to be raised
  572. - an infinite result from finite inputs causes OverflowError to be
  573. raised if can_overflow is 1, or raises ValueError if can_overflow
  574. is 0.
  575. - if the result is finite and errno == EDOM then ValueError is
  576. raised
  577. - if the result is finite and nonzero and errno == ERANGE then
  578. OverflowError is raised
  579. The last rule is used to catch overflow on platforms which follow
  580. C89 but for which HUGE_VAL is not an infinity.
  581. For the majority of one-argument functions these rules are enough
  582. to ensure that Python's functions behave as specified in 'Annex F'
  583. of the C99 standard, with the 'invalid' and 'divide-by-zero'
  584. floating-point exceptions mapping to Python's ValueError and the
  585. 'overflow' floating-point exception mapping to OverflowError.
  586. math_1 only works for functions that don't have singularities *and*
  587. the possibility of overflow; fortunately, that covers everything we
  588. care about right now.
  589. */
  590. static PyObject *
  591. math_1(PyObject *arg, double (*func) (double), int can_overflow)
  592. {
  593. double x, r;
  594. x = PyFloat_AsDouble(arg);
  595. if (x == -1.0 && PyErr_Occurred())
  596. return NULL;
  597. errno = 0;
  598. PyFPE_START_PROTECT("in math_1", return 0);
  599. r = (*func)(x);
  600. PyFPE_END_PROTECT(r);
  601. if (Py_IS_NAN(r)) {
  602. if (!Py_IS_NAN(x))
  603. errno = EDOM;
  604. else
  605. errno = 0;
  606. }
  607. else if (Py_IS_INFINITY(r)) {
  608. if (Py_IS_FINITE(x))
  609. errno = can_overflow ? ERANGE : EDOM;
  610. else
  611. errno = 0;
  612. }
  613. if (errno && is_error(r))
  614. return NULL;
  615. else
  616. return PyFloat_FromDouble(r);
  617. }
  618. /* variant of math_1, to be used when the function being wrapped is known to
  619. set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
  620. errno = ERANGE for overflow). */
  621. static PyObject *
  622. math_1a(PyObject *arg, double (*func) (double))
  623. {
  624. double x, r;
  625. x = PyFloat_AsDouble(arg);
  626. if (x == -1.0 && PyErr_Occurred())
  627. return NULL;
  628. errno = 0;
  629. PyFPE_START_PROTECT("in math_1a", return 0);
  630. r = (*func)(x);
  631. PyFPE_END_PROTECT(r);
  632. if (errno && is_error(r))
  633. return NULL;
  634. return PyFloat_FromDouble(r);
  635. }
  636. /*
  637. math_2 is used to wrap a libm function f that takes two double
  638. arguments and returns a double.
  639. The error reporting follows these rules, which are designed to do
  640. the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
  641. platforms.
  642. - a NaN result from non-NaN inputs causes ValueError to be raised
  643. - an infinite result from finite inputs causes OverflowError to be
  644. raised.
  645. - if the result is finite and errno == EDOM then ValueError is
  646. raised
  647. - if the result is finite and nonzero and errno == ERANGE then
  648. OverflowError is raised
  649. The last rule is used to catch overflow on platforms which follow
  650. C89 but for which HUGE_VAL is not an infinity.
  651. For most two-argument functions (copysign, fmod, hypot, atan2)
  652. these rules are enough to ensure that Python's functions behave as
  653. specified in 'Annex F' of the C99 standard, with the 'invalid' and
  654. 'divide-by-zero' floating-point exceptions mapping to Python's
  655. ValueError and the 'overflow' floating-point exception mapping to
  656. OverflowError.
  657. */
  658. static PyObject *
  659. math_2(PyObject *args, double (*func) (double, double), char *funcname)
  660. {
  661. PyObject *ox, *oy;
  662. double x, y, r;
  663. if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
  664. return NULL;
  665. x = PyFloat_AsDouble(ox);
  666. y = PyFloat_AsDouble(oy);
  667. if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
  668. return NULL;
  669. errno = 0;
  670. PyFPE_START_PROTECT("in math_2", return 0);
  671. r = (*func)(x, y);
  672. PyFPE_END_PROTECT(r);
  673. if (Py_IS_NAN(r)) {
  674. if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
  675. errno = EDOM;
  676. else
  677. errno = 0;
  678. }
  679. else if (Py_IS_INFINITY(r)) {
  680. if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
  681. errno = ERANGE;
  682. else
  683. errno = 0;
  684. }
  685. if (errno && is_error(r))
  686. return NULL;
  687. else
  688. return PyFloat_FromDouble(r);
  689. }
  690. #define FUNC1(funcname, func, can_overflow, docstring) \
  691. static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
  692. return math_1(args, func, can_overflow); \
  693. }\
  694. PyDoc_STRVAR(math_##funcname##_doc, docstring);
  695. #define FUNC1A(funcname, func, docstring) \
  696. static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
  697. return math_1a(args, func); \
  698. }\
  699. PyDoc_STRVAR(math_##funcname##_doc, docstring);
  700. #define FUNC2(funcname, func, docstring) \
  701. static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
  702. return math_2(args, func, #funcname); \
  703. }\
  704. PyDoc_STRVAR(math_##funcname##_doc, docstring);
  705. FUNC1(acos, acos, 0,
  706. "acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
  707. FUNC1(acosh, m_acosh, 0,
  708. "acosh(x)\n\nReturn the hyperbolic arc cosine (measured in radians) of x.")
  709. FUNC1(asin, asin, 0,
  710. "asin(x)\n\nReturn the arc sine (measured in radians) of x.")
  711. FUNC1(asinh, m_asinh, 0,
  712. "asinh(x)\n\nReturn the hyperbolic arc sine (measured in radians) of x.")
  713. FUNC1(atan, atan, 0,
  714. "atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
  715. FUNC2(atan2, m_atan2,
  716. "atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
  717. "Unlike atan(y/x), the signs of both x and y are considered.")
  718. FUNC1(atanh, m_atanh, 0,
  719. "atanh(x)\n\nReturn the hyperbolic arc tangent (measured in radians) of x.")
  720. FUNC1(ceil, ceil, 0,
  721. "ceil(x)\n\nReturn the ceiling of x as a float.\n"
  722. "This is the smallest integral value >= x.")
  723. FUNC2(copysign, copysign,
  724. "copysign(x, y)\n\nReturn x with the sign of y.")
  725. FUNC1(cos, cos, 0,
  726. "cos(x)\n\nReturn the cosine of x (measured in radians).")
  727. FUNC1(cosh, cosh, 1,
  728. "cosh(x)\n\nReturn the hyperbolic cosine of x.")
  729. FUNC1A(erf, m_erf,
  730. "erf(x)\n\nError function at x.")
  731. FUNC1A(erfc, m_erfc,
  732. "erfc(x)\n\nComplementary error function at x.")
  733. FUNC1(exp, exp, 1,
  734. "exp(x)\n\nReturn e raised to the power of x.")
  735. FUNC1(expm1, m_expm1, 1,
  736. "expm1(x)\n\nReturn exp(x)-1.\n"
  737. "This function avoids the loss of precision involved in the direct "
  738. "evaluation of exp(x)-1 for small x.")
  739. FUNC1(fabs, fabs, 0,
  740. "fabs(x)\n\nReturn the absolute value of the float x.")
  741. FUNC1(floor, floor, 0,
  742. "floor(x)\n\nReturn the floor of x as a float.\n"
  743. "This is the largest integral value <= x.")
  744. FUNC1A(gamma, m_tgamma,
  745. "gamma(x)\n\nGamma function at x.")
  746. FUNC1A(lgamma, m_lgamma,
  747. "lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
  748. FUNC1(log1p, m_log1p, 1,
  749. "log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
  750. "The result is computed in a way which is accurate for x near zero.")
  751. FUNC1(sin, sin, 0,
  752. "sin(x)\n\nReturn the sine of x (measured in radians).")
  753. FUNC1(sinh, sinh, 1,
  754. "sinh(x)\n\nReturn the hyperbolic sine of x.")
  755. FUNC1(sqrt, sqrt, 0,
  756. "sqrt(x)\n\nReturn the square root of x.")
  757. FUNC1(tan, tan, 0,
  758. "tan(x)\n\nReturn the tangent of x (measured in radians).")
  759. FUNC1(tanh, tanh, 0,
  760. "tanh(x)\n\nReturn the hyperbolic tangent of x.")
  761. /* Precision summation function as msum() by Raymond Hettinger in
  762. <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
  763. enhanced with the exact partials sum and roundoff from Mark
  764. Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
  765. See those links for more details, proofs and other references.
  766. Note 1: IEEE 754R floating point semantics are assumed,
  767. but the current implementation does not re-establish special
  768. value semantics across iterations (i.e. handling -Inf + Inf).
  769. Note 2: No provision is made for intermediate overflow handling;
  770. therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
  771. sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
  772. overflow of the first partial sum.
  773. Note 3: The intermediate values lo, yr, and hi are declared volatile so
  774. aggressive compilers won't algebraically reduce lo to always be exactly 0.0.
  775. Also, the volatile declaration forces the values to be stored in memory as
  776. regular doubles instead of extended long precision (80-bit) values. This
  777. prevents double rounding because any addition or subtraction of two doubles
  778. can be resolved exactly into double-sized hi and lo values. As long as the
  779. hi value gets forced into a double before yr and lo are computed, the extra
  780. bits in downstream extended precision operations (x87 for example) will be
  781. exactly zero and therefore can be losslessly stored back into a double,
  782. thereby preventing double rounding.
  783. Note 4: A similar implementation is in Modules/cmathmodule.c.
  784. Be sure to update both when making changes.
  785. Note 5: The signature of math.fsum() differs from __builtin__.sum()
  786. because the start argument doesn't make sense in the context of
  787. accurate summation. Since the partials table is collapsed before
  788. returning a result, sum(seq2, start=sum(seq1)) may not equal the
  789. accurate result returned by sum(itertools.chain(seq1, seq2)).
  790. */
  791. #define NUM_PARTIALS 32 /* initial partials array size, on stack */
  792. /* Extend the partials array p[] by doubling its size. */
  793. static int /* non-zero on error */
  794. _fsum_realloc(double **p_ptr, Py_ssize_t n,
  795. double *ps, Py_ssize_t *m_ptr)
  796. {
  797. void *v = NULL;
  798. Py_ssize_t m = *m_ptr;
  799. m += m; /* double */
  800. if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
  801. double *p = *p_ptr;
  802. if (p == ps) {
  803. v = PyMem_Malloc(sizeof(double) * m);
  804. if (v != NULL)
  805. memcpy(v, ps, sizeof(double) * n);
  806. }
  807. else
  808. v = PyMem_Realloc(p, sizeof(double) * m);
  809. }
  810. if (v == NULL) { /* size overflow or no memory */
  811. PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
  812. return 1;
  813. }
  814. *p_ptr = (double*) v;
  815. *m_ptr = m;
  816. return 0;
  817. }
  818. /* Full precision summation of a sequence of floats.
  819. def msum(iterable):
  820. partials = [] # sorted, non-overlapping partial sums
  821. for x in iterable:
  822. i = 0
  823. for y in partials:
  824. if abs(x) < abs(y):
  825. x, y = y, x
  826. hi = x + y
  827. lo = y - (hi - x)
  828. if lo:
  829. partials[i] = lo
  830. i += 1
  831. x = hi
  832. partials[i:] = [x]
  833. return sum_exact(partials)
  834. Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
  835. are exactly equal to x+y. The inner loop applies hi/lo summation to each
  836. partial so that the list of partial sums remains exact.
  837. Sum_exact() adds the partial sums exactly and correctly rounds the final
  838. result (using the round-half-to-even rule). The items in partials remain
  839. non-zero, non-special, non-overlapping and strictly increasing in
  840. magnitude, but possibly not all having the same sign.
  841. Depends on IEEE 754 arithmetic guarantees and half-even rounding.
  842. */
  843. static PyObject*
  844. math_fsum(PyObject *self, PyObject *seq)
  845. {
  846. PyObject *item, *iter, *sum = NULL;
  847. Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
  848. double x, y, t, ps[NUM_PARTIALS], *p = ps;
  849. double xsave, special_sum = 0.0, inf_sum = 0.0;
  850. volatile double hi, yr, lo;
  851. iter = PyObject_GetIter(seq);
  852. if (iter == NULL)
  853. return NULL;
  854. PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
  855. for(;;) { /* for x in iterable */
  856. assert(0 <= n && n <= m);
  857. assert((m == NUM_PARTIALS && p == ps) ||
  858. (m > NUM_PARTIALS && p != NULL));
  859. item = PyIter_Next(iter);
  860. if (item == NULL) {
  861. if (PyErr_Occurred())
  862. goto _fsum_error;
  863. break;
  864. }
  865. x = PyFloat_AsDouble(item);
  866. Py_DECREF(item);
  867. if (PyErr_Occurred())
  868. goto _fsum_error;
  869. xsave = x;
  870. for (i = j = 0; j < n; j++) { /* for y in partials */
  871. y = p[j];
  872. if (fabs(x) < fabs(y)) {
  873. t = x; x = y; y = t;
  874. }
  875. hi = x + y;
  876. yr = hi - x;
  877. lo = y - yr;
  878. if (lo != 0.0)
  879. p[i++] = lo;
  880. x = hi;
  881. }
  882. n = i; /* ps[i:] = [x] */
  883. if (x != 0.0) {
  884. if (! Py_IS_FINITE(x)) {
  885. /* a nonfinite x could arise either as
  886. a result of intermediate overflow, or
  887. as a result of a nan or inf in the
  888. summands */
  889. if (Py_IS_FINITE(xsave)) {
  890. PyErr_SetString(PyExc_OverflowError,
  891. "intermediate overflow in fsum");
  892. goto _fsum_error;
  893. }
  894. if (Py_IS_INFINITY(xsave))
  895. inf_sum += xsave;
  896. special_sum += xsave;
  897. /* reset partials */
  898. n = 0;
  899. }
  900. else if (n >= m && _fsum_realloc(&p, n, ps, &m))
  901. goto _fsum_error;
  902. else
  903. p[n++] = x;
  904. }
  905. }
  906. if (special_sum != 0.0) {
  907. if (Py_IS_NAN(inf_sum))
  908. PyErr_SetString(PyExc_ValueError,
  909. "-inf + inf in fsum");
  910. else
  911. sum = PyFloat_FromDouble(special_sum);
  912. goto _fsum_error;
  913. }
  914. hi = 0.0;
  915. if (n > 0) {
  916. hi = p[--n];
  917. /* sum_exact(ps, hi) from the top, stop when the sum becomes
  918. inexact. */
  919. while (n > 0) {
  920. x = hi;
  921. y = p[--n];
  922. assert(fabs(y) < fabs(x));
  923. hi = x + y;
  924. yr = hi - x;
  925. lo = y - yr;
  926. if (lo != 0.0)
  927. break;
  928. }
  929. /* Make half-even rounding work across multiple partials.
  930. Needed so that sum([1e-16, 1, 1e16]) will round-up the last
  931. digit to two instead of down to zero (the 1e-16 makes the 1
  932. slightly closer to two). With a potential 1 ULP rounding
  933. error fixed-up, math.fsum() can guarantee commutativity. */
  934. if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
  935. (lo > 0.0 && p[n-1] > 0.0))) {
  936. y = lo * 2.0;
  937. x = hi + y;
  938. yr = x - hi;
  939. if (y == yr)
  940. hi = x;
  941. }
  942. }
  943. sum = PyFloat_FromDouble(hi);
  944. _fsum_error:
  945. PyFPE_END_PROTECT(hi)
  946. Py_DECREF(iter);
  947. if (p != ps)
  948. PyMem_Free(p);
  949. return sum;
  950. }
  951. #undef NUM_PARTIALS
  952. PyDoc_STRVAR(math_fsum_doc,
  953. "fsum(iterable)\n\n\
  954. Return an accurate floating point sum of values in the iterable.\n\
  955. Assumes IEEE-754 floating point arithmetic.");
  956. static PyObject *
  957. math_factorial(PyObject *self, PyObject *arg)
  958. {
  959. long i, x;
  960. PyObject *result, *iobj, *newresult;
  961. if (PyFloat_Check(arg)) {
  962. PyObject *lx;
  963. double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
  964. if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
  965. PyErr_SetString(PyExc_ValueError,
  966. "factorial() only accepts integral values");
  967. return NULL;
  968. }
  969. lx = PyLong_FromDouble(dx);
  970. if (lx == NULL)
  971. return NULL;
  972. x = PyLong_AsLong(lx);
  973. Py_DECREF(lx);
  974. }
  975. else
  976. x = PyInt_AsLong(arg);
  977. if (x == -1 && PyErr_Occurred())
  978. return NULL;
  979. if (x < 0) {
  980. PyErr_SetString(PyExc_ValueError,
  981. "factorial() not defined for negative values");
  982. return NULL;
  983. }
  984. result = (PyObject *)PyInt_FromLong(1);
  985. if (result == NULL)
  986. return NULL;
  987. for (i=1 ; i<=x ; i++) {
  988. iobj = (PyObject *)PyInt_FromLong(i);
  989. if (iobj == NULL)
  990. goto error;
  991. newresult = PyNumber_Multiply(result, iobj);
  992. Py_DECREF(iobj);
  993. if (newresult == NULL)
  994. goto error;
  995. Py_DECREF(result);
  996. result = newresult;
  997. }
  998. return result;
  999. error:
  1000. Py_DECREF(result);
  1001. return NULL;
  1002. }
  1003. PyDoc_STRVAR(math_factorial_doc,
  1004. "factorial(x) -> Integral\n"
  1005. "\n"
  1006. "Find x!. Raise a ValueError if x is negative or non-integral.");
  1007. static PyObject *
  1008. math_trunc(PyObject *self, PyObject *number)
  1009. {
  1010. return PyObject_CallMethod(number, "__trunc__", NULL);
  1011. }
  1012. PyDoc_STRVAR(math_trunc_doc,
  1013. "trunc(x:Real) -> Integral\n"
  1014. "\n"
  1015. "Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
  1016. static PyObject *
  1017. math_frexp(PyObject *self, PyObject *arg)
  1018. {
  1019. int i;
  1020. double x = PyFloat_AsDouble(arg);
  1021. if (x == -1.0 && PyErr_Occurred())
  1022. return NULL;
  1023. /* deal with special cases directly, to sidestep platform
  1024. differences */
  1025. if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
  1026. i = 0;
  1027. }
  1028. else {
  1029. PyFPE_START_PROTECT("in math_frexp", return 0);
  1030. x = frexp(x, &i);
  1031. PyFPE_END_PROTECT(x);
  1032. }
  1033. return Py_BuildValue("(di)", x, i);
  1034. }
  1035. PyDoc_STRVAR(math_frexp_doc,
  1036. "frexp(x)\n"
  1037. "\n"
  1038. "Return the mantissa and exponent of x, as pair (m, e).\n"
  1039. "m is a float and e is an int, such that x = m * 2.**e.\n"
  1040. "If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.");
  1041. static PyObject *
  1042. math_ldexp(PyObject *self, PyObject *args)
  1043. {
  1044. double x, r;
  1045. PyObject *oexp;
  1046. long exp;
  1047. int overflow;
  1048. if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
  1049. return NULL;
  1050. if (PyLong_Check(oexp) || PyInt_Check(oexp)) {
  1051. /* on overflow, replace exponent with either LONG_MAX
  1052. or LONG_MIN, depending on the sign. */
  1053. exp = PyLong_AsLongAndOverflow(oexp, &overflow);
  1054. if (exp == -1 && PyErr_Occurred())
  1055. return NULL;
  1056. if (overflow)
  1057. exp = overflow < 0 ? LONG_MIN : LONG_MAX;
  1058. }
  1059. else {
  1060. PyErr_SetString(PyExc_TypeError,
  1061. "Expected an int or long as second argument "
  1062. "to ldexp.");
  1063. return NULL;
  1064. }
  1065. if (x == 0. || !Py_IS_FINITE(x)) {
  1066. /* NaNs, zeros and infinities are returned unchanged */
  1067. r = x;
  1068. errno = 0;
  1069. } else if (exp > INT_MAX) {
  1070. /* overflow */
  1071. r = copysign(Py_HUGE_VAL, x);
  1072. errno = ERANGE;
  1073. } else if (exp < INT_MIN) {
  1074. /* underflow to +-0 */
  1075. r = copysign(0., x);
  1076. errno = 0;
  1077. } else {
  1078. errno = 0;
  1079. PyFPE_START_PROTECT("in math_ldexp", return 0);
  1080. r = ldexp(x, (int)exp);
  1081. PyFPE_END_PROTECT(r);
  1082. if (Py_IS_INFINITY(r))
  1083. errno = ERANGE;
  1084. }
  1085. if (errno && is_error(r))
  1086. return NULL;
  1087. return PyFloat_FromDouble(r);
  1088. }
  1089. PyDoc_STRVAR(math_ldexp_doc,
  1090. "ldexp(x, i)\n\n\
  1091. Return x * (2**i).");
  1092. static PyObject *
  1093. math_modf(PyObject *self, PyObject *arg)
  1094. {
  1095. double y, x = PyFloat_AsDouble(arg);
  1096. if (x == -1.0 && PyErr_Occurred())
  1097. return NULL;
  1098. /* some platforms don't do the right thing for NaNs and
  1099. infinities, so we take care of special cases directly. */
  1100. if (!Py_IS_FINITE(x)) {
  1101. if (Py_IS_INFINITY(x))
  1102. return Py_BuildValue("(dd)", copysign(0., x), x);
  1103. else if (Py_IS_NAN(x))
  1104. return Py_BuildValue("(dd)", x, x);
  1105. }
  1106. errno = 0;
  1107. PyFPE_START_PROTECT("in math_modf", return 0);
  1108. x = modf(x, &y);
  1109. PyFPE_END_PROTECT(x);
  1110. return Py_BuildValue("(dd)", x, y);
  1111. }
  1112. PyDoc_STRVAR(math_modf_doc,
  1113. "modf(x)\n"
  1114. "\n"
  1115. "Return the fractional and integer parts of x. Both results carry the sign\n"
  1116. "of x and are floats.");
  1117. /* A decent logarithm is easy to compute even for huge longs, but libm can't
  1118. do that by itself -- loghelper can. func is log or log10, and name is
  1119. "log" or "log10". Note that overflow of the result isn't possible: a long
  1120. can contain no more than INT_MAX * SHIFT bits, so has value certainly less
  1121. than 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
  1122. small enough to fit in an IEEE single. log and log10 are even smaller.
  1123. However, intermediate overflow is possible for a long if the number of bits
  1124. in that long is larger than PY_SSIZE_T_MAX. */
  1125. static PyObject*
  1126. loghelper(PyObject* arg, double (*func)(double), char *funcname)
  1127. {
  1128. /* If it is long, do it ourselves. */
  1129. if (PyLong_Check(arg)) {
  1130. double x;
  1131. Py_ssize_t e;
  1132. x = _PyLong_Frexp((PyLongObject *)arg, &e);
  1133. if (x == -1.0 && PyErr_Occurred())
  1134. return NULL;
  1135. if (x <= 0.0) {
  1136. PyErr_SetString(PyExc_ValueError,
  1137. "math domain error");
  1138. return NULL;
  1139. }
  1140. /* Special case for log(1), to make sure we get an
  1141. exact result there. */
  1142. if (e == 1 && x == 0.5)
  1143. return PyFloat_FromDouble(0.0);
  1144. /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
  1145. x = func(x) + func(2.0) * e;
  1146. return PyFloat_FromDouble(x);
  1147. }
  1148. /* Else let libm handle it by itself. */
  1149. return math_1(arg, func, 0);
  1150. }
  1151. static PyObject *
  1152. math_log(PyObject *self, PyObject *args)
  1153. {
  1154. PyObject *arg;
  1155. PyObject *base = NULL;
  1156. PyObject *num, *den;
  1157. PyObject *ans;
  1158. if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
  1159. return NULL;
  1160. num = loghelper(arg, m_log, "log");
  1161. if (num == NULL || base == NULL)
  1162. return num;
  1163. den = loghelper(base, m_log, "log");
  1164. if (den == NULL) {
  1165. Py_DECREF(num);
  1166. return NULL;
  1167. }
  1168. ans = PyNumber_Divide(num, den);
  1169. Py_DECREF(num);
  1170. Py_DECREF(den);
  1171. return ans;
  1172. }
  1173. PyDoc_STRVAR(math_log_doc,
  1174. "log(x[, base])\n\n\
  1175. Return the logarithm of x to the given base.\n\
  1176. If the base not specified, returns the natural logarithm (base e) of x.");
  1177. static PyObject *
  1178. math_log10(PyObject *self, PyObject *arg)
  1179. {
  1180. return loghelper(arg, m_log10, "log10");
  1181. }
  1182. PyDoc_STRVAR(math_log10_doc,
  1183. "log10(x)\n\nReturn the base 10 logarithm of x.");
  1184. static PyObject *
  1185. math_fmod(PyObject *self, PyObject *args)
  1186. {
  1187. PyObject *ox, *oy;
  1188. double r, x, y;
  1189. if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
  1190. return NULL;
  1191. x = PyFloat_AsDouble(ox);
  1192. y = PyFloat_AsDouble(oy);
  1193. if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
  1194. return NULL;
  1195. /* fmod(x, +/-Inf) returns x for finite x. */
  1196. if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
  1197. return PyFloat_FromDouble(x);
  1198. errno = 0;
  1199. PyFPE_START_PROTECT("in math_fmod", return 0);
  1200. r = fmod(x, y);
  1201. PyFPE_END_PROTECT(r);
  1202. if (Py_IS_NAN(r)) {
  1203. if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
  1204. errno = EDOM;
  1205. else
  1206. errno = 0;
  1207. }
  1208. if (errno && is_error(r))
  1209. return NULL;
  1210. else
  1211. return PyFloat_FromDouble(r);
  1212. }
  1213. PyDoc_STRVAR(math_fmod_doc,
  1214. "fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
  1215. " x % y may differ.");
  1216. static PyObject *
  1217. math_hypot(PyObject *self, PyObject *args)
  1218. {
  1219. PyObject *ox, *oy;
  1220. double r, x, y;
  1221. if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
  1222. return NULL;
  1223. x = PyFloat_AsDouble(ox);
  1224. y = PyFloat_AsDouble(oy);
  1225. if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
  1226. return NULL;
  1227. /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
  1228. if (Py_IS_INFINITY(x))
  1229. return PyFloat_FromDouble(fabs(x));
  1230. if (Py_IS_INFINITY(y))
  1231. return PyFloat_FromDouble(fabs(y));
  1232. errno = 0;
  1233. PyFPE_START_PROTECT("in math_hypot", return 0);
  1234. r = hypot(x, y);
  1235. PyFPE_END_PROTECT(r);
  1236. if (Py_IS_NAN(r)) {
  1237. if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
  1238. errno = EDOM;
  1239. else
  1240. errno = 0;
  1241. }
  1242. else if (Py_IS_INFINITY(r)) {
  1243. if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
  1244. errno = ERANGE;
  1245. else
  1246. errno = 0;
  1247. }
  1248. if (errno && is_error(r))
  1249. return NULL;
  1250. else
  1251. return PyFloat_FromDouble(r);
  1252. }
  1253. PyDoc_STRVAR(math_hypot_doc,
  1254. "hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
  1255. /* pow can't use math_2, but needs its own wrapper: the problem is
  1256. that an infinite result can arise either as a result of overflow
  1257. (in which case OverflowError should be raised) or as a result of
  1258. e.g. 0.**-5. (for which ValueError needs to be raised.)
  1259. */
  1260. static PyObject *
  1261. math_pow(PyObject *self, PyObject *args)
  1262. {
  1263. PyObject *ox, *oy;
  1264. double r, x, y;
  1265. int odd_y;
  1266. if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
  1267. return NULL;
  1268. x = PyFloat_AsDouble(ox);
  1269. y = PyFloat_AsDouble(oy);
  1270. if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
  1271. return NULL;
  1272. /* deal directly with IEEE specials, to cope with problems on various
  1273. platforms whose semantics don't exactly match C99 */
  1274. r = 0.; /* silence compiler warning */
  1275. if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
  1276. errno = 0;
  1277. if (Py_IS_NAN(x))
  1278. r = y == 0. ? 1. : x; /* NaN**0 = 1 */
  1279. else if (Py_IS_NAN(y))
  1280. r = x == 1. ? 1. : y; /* 1**NaN = 1 */
  1281. else if (Py_IS_INFINITY(x)) {
  1282. odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
  1283. if (y > 0.)
  1284. r = odd_y ? x : fabs(x);
  1285. else if (y == 0.)
  1286. r = 1.;
  1287. else /* y < 0. */
  1288. r = odd_y ? copysign(0., x) : 0.;
  1289. }
  1290. else if (Py_IS_INFINITY(y)) {
  1291. if (fabs(x) == 1.0)
  1292. r = 1.;
  1293. else if (y > 0. && fabs(x) > 1.0)
  1294. r = y;
  1295. else if (y < 0. && fabs(x) < 1.0) {
  1296. r = -y; /* result is +inf */
  1297. if (x == 0.) /* 0**-inf: divide-by-zero */
  1298. errno = EDOM;
  1299. }
  1300. else
  1301. r = 0.;
  1302. }
  1303. }
  1304. else {
  1305. /* let libm handle finite**finite */
  1306. errno = 0;
  1307. PyFPE_START_PROTECT("in math_pow", return 0);
  1308. r = pow(x, y);
  1309. PyFPE_END_PROTECT(r);
  1310. /* a NaN result should arise only from (-ve)**(finite
  1311. non-integer); in this case we want to raise ValueError. */
  1312. if (!Py_IS_FINITE(r)) {
  1313. if (Py_IS_NAN(r)) {
  1314. errno = EDOM;
  1315. }
  1316. /*
  1317. an infinite result here arises either from:
  1318. (A) (+/-0.)**negative (-> divide-by-zero)
  1319. (B) overflow of x**y with x and y finite
  1320. */
  1321. else if (Py_IS_INFINITY(r)) {
  1322. if (x == 0.)
  1323. errno = EDOM;
  1324. else
  1325. errno = ERANGE;
  1326. }
  1327. }
  1328. }
  1329. if (errno && is_error(r))
  1330. return NULL;
  1331. else
  1332. return PyFloat_FromDouble(r);
  1333. }
  1334. PyDoc_STRVAR(math_pow_doc,
  1335. "pow(x, y)\n\nReturn x**y (x to the power of y).");
  1336. static const double degToRad = Py_MATH_PI / 180.0;
  1337. static const double radToDeg = 180.0 / Py_MATH_PI;
  1338. static PyObject *
  1339. math_degrees(PyObject *self, PyObject *arg)
  1340. {
  1341. double x = PyFloat_AsDouble(arg);
  1342. if (x == -1.0 && PyErr_Occurred())
  1343. return NULL;
  1344. return PyFloat_FromDouble(x * radToDeg);
  1345. }
  1346. PyDoc_STRVAR(math_degrees_doc,
  1347. "degrees(x)\n\n\
  1348. Convert angle x from radians to degrees.");
  1349. static PyObject *
  1350. math_radians(PyObject *self, PyObject *arg)
  1351. {
  1352. double x = PyFloat_AsDouble(arg);
  1353. if (x == -1.0 && PyErr_Occurred())
  1354. return NULL;
  1355. return PyFloat_FromDouble(x * degToRad);
  1356. }
  1357. PyDoc_STRVAR(math_radians_doc,
  1358. "radians(x)\n\n\
  1359. Convert angle x from degrees to radians.");
  1360. static PyObject *
  1361. math_isnan(PyObject *self, PyObject *arg)
  1362. {
  1363. double x = PyFloat_AsDouble(arg);
  1364. if (x == -1.0 && PyErr_Occurred())
  1365. return NULL;
  1366. return PyBool_FromLong((long)Py_IS_NAN(x));
  1367. }
  1368. PyDoc_STRVAR(math_isnan_doc,
  1369. "isnan(x) -> bool\n\n\
  1370. Check if float x is not a number (NaN).");
  1371. static PyObject *
  1372. math_isinf(PyObject *self, PyObject *arg)
  1373. {
  1374. double x = PyFloat_AsDouble(arg);
  1375. if (x == -1.0 && PyErr_Occurred())
  1376. return NULL;
  1377. return PyBool_FromLong((long)Py_IS_INFINITY(x));
  1378. }
  1379. PyDoc_STRVAR(math_isinf_doc,
  1380. "isinf(x) -> bool\n\n\
  1381. Check if float x is infinite (positive or negative).");
  1382. static PyMethodDef math_methods[] = {
  1383. {"acos", math_acos, METH_O, math_acos_doc},
  1384. {"acosh", math_acosh, METH_O, math_acosh_doc},
  1385. {"asin", math_asin, METH_O, math_asin_doc},
  1386. {"asinh", math_asinh, METH_O, math_asinh_doc},
  1387. {"atan", math_atan, METH_O, math_atan_doc},
  1388. {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
  1389. {"atanh", math_atanh, METH_O, math_atanh_doc},
  1390. {"ceil", math_ceil, METH_O, math_ceil_doc},
  1391. {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
  1392. {"cos", math_cos, METH_O, math_cos_doc},
  1393. {"cosh", math_cosh, METH_O, math_cosh_doc},
  1394. {"degrees", math_degrees, METH_O, math_degrees_doc},
  1395. {"erf", math_erf, METH_O, math_erf_doc},
  1396. {"erfc", math_erfc, METH_O, math_erfc_doc},
  1397. {"exp", math_exp, METH_O, math_exp_doc},
  1398. {"expm1", math_expm1, METH_O, math_expm1_doc},
  1399. {"fabs", math_fabs, METH_O, math_fabs_doc},
  1400. {"factorial", math_factorial, METH_O, math_factorial_doc},
  1401. {"floor", math_floor, METH_O, math_floor_doc},
  1402. {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
  1403. {"frexp", math_frexp, METH_O, math_frexp_doc},
  1404. {"fsum", math_fsum, METH_O, math_fsum_doc},
  1405. {"gamma", math_gamma, METH_O, math_gamma_doc},
  1406. {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
  1407. {"isinf", math_isinf, METH_O, math_isinf_doc},
  1408. {"isnan", math_isnan, METH_O, math_isnan_doc},
  1409. {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
  1410. {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
  1411. {"log", math_log, METH_VARARGS, math_log_doc},
  1412. {"log1p", math_log1p, METH_O, math_log1p_doc},
  1413. {"log10", math_log10, METH_O, math_log10_doc},
  1414. {"modf", math_modf, METH_O, math_modf_doc},
  1415. {"pow", math_pow, METH_VARARGS, math_pow_doc},
  1416. {"radians", math_radians, METH_O, math_radians_doc},
  1417. {"sin", math_sin, METH_O, math_sin_doc},
  1418. {"sinh", math_sinh, METH_O, math_sinh_doc},
  1419. {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
  1420. {"tan", math_tan, METH_O, math_tan_doc},
  1421. {"tanh", math_tanh, METH_O, math_tanh_doc},
  1422. {"trunc", math_trunc, METH_O, math_trunc_doc},
  1423. {NULL, NULL} /* sentinel */
  1424. };
  1425. PyDoc_STRVAR(module_doc,
  1426. "This module is always available. It provides access to the\n"
  1427. "mathematical functions defined by the C standard.");
  1428. PyMODINIT_FUNC
  1429. initmath(void)
  1430. {
  1431. PyObject *m;
  1432. m = Py_InitModule3("math", math_methods, module_doc);
  1433. if (m == NULL)
  1434. goto finally;
  1435. PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
  1436. PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
  1437. finally:
  1438. return;
  1439. }