1:mod:`math` --- Mathematical functions 2====================================== 3 4.. module:: math 5 :synopsis: Mathematical functions (sin() etc.). 6 7.. testsetup:: 8 9 from math import fsum 10 11-------------- 12 13This module provides access to the mathematical functions defined by the C 14standard. 15 16These functions cannot be used with complex numbers; use the functions of the 17same name from the :mod:`cmath` module if you require support for complex 18numbers. The distinction between functions which support complex numbers and 19those which don't is made since most users do not want to learn quite as much 20mathematics as required to understand complex numbers. Receiving an exception 21instead of a complex result allows earlier detection of the unexpected complex 22number used as a parameter, so that the programmer can determine how and why it 23was generated in the first place. 24 25The following functions are provided by this module. Except when explicitly 26noted otherwise, all return values are floats. 27 28 29Number-theoretic and representation functions 30--------------------------------------------- 31 32.. function:: ceil(x) 33 34 Return the ceiling of *x*, the smallest integer greater than or equal to *x*. 35 If *x* is not a float, delegates to ``x.__ceil__()``, which should return an 36 :class:`~numbers.Integral` value. 37 38 39.. function:: comb(n, k) 40 41 Return the number of ways to choose *k* items from *n* items without repetition 42 and without order. 43 44 Evaluates to ``n! / (k! * (n - k)!)`` when ``k <= n`` and evaluates 45 to zero when ``k > n``. 46 47 Also called the binomial coefficient because it is equivalent 48 to the coefficient of k-th term in polynomial expansion of the 49 expression ``(1 + x) ** n``. 50 51 Raises :exc:`TypeError` if either of the arguments are not integers. 52 Raises :exc:`ValueError` if either of the arguments are negative. 53 54 .. versionadded:: 3.8 55 56 57.. function:: copysign(x, y) 58 59 Return a float with the magnitude (absolute value) of *x* but the sign of 60 *y*. On platforms that support signed zeros, ``copysign(1.0, -0.0)`` 61 returns *-1.0*. 62 63 64.. function:: fabs(x) 65 66 Return the absolute value of *x*. 67 68 69.. function:: factorial(x) 70 71 Return *x* factorial as an integer. Raises :exc:`ValueError` if *x* is not integral or 72 is negative. 73 74 75.. function:: floor(x) 76 77 Return the floor of *x*, the largest integer less than or equal to *x*. 78 If *x* is not a float, delegates to ``x.__floor__()``, which should return an 79 :class:`~numbers.Integral` value. 80 81 82.. function:: fmod(x, y) 83 84 Return ``fmod(x, y)``, as defined by the platform C library. Note that the 85 Python expression ``x % y`` may not return the same result. The intent of the C 86 standard is that ``fmod(x, y)`` be exactly (mathematically; to infinite 87 precision) equal to ``x - n*y`` for some integer *n* such that the result has 88 the same sign as *x* and magnitude less than ``abs(y)``. Python's ``x % y`` 89 returns a result with the sign of *y* instead, and may not be exactly computable 90 for float arguments. For example, ``fmod(-1e-100, 1e100)`` is ``-1e-100``, but 91 the result of Python's ``-1e-100 % 1e100`` is ``1e100-1e-100``, which cannot be 92 represented exactly as a float, and rounds to the surprising ``1e100``. For 93 this reason, function :func:`fmod` is generally preferred when working with 94 floats, while Python's ``x % y`` is preferred when working with integers. 95 96 97.. function:: frexp(x) 98 99 Return the mantissa and exponent of *x* as the pair ``(m, e)``. *m* is a float 100 and *e* is an integer such that ``x == m * 2**e`` exactly. If *x* is zero, 101 returns ``(0.0, 0)``, otherwise ``0.5 <= abs(m) < 1``. This is used to "pick 102 apart" the internal representation of a float in a portable way. 103 104 105.. function:: fsum(iterable) 106 107 Return an accurate floating point sum of values in the iterable. Avoids 108 loss of precision by tracking multiple intermediate partial sums:: 109 110 >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 111 0.9999999999999999 112 >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 113 1.0 114 115 The algorithm's accuracy depends on IEEE-754 arithmetic guarantees and the 116 typical case where the rounding mode is half-even. On some non-Windows 117 builds, the underlying C library uses extended precision addition and may 118 occasionally double-round an intermediate sum causing it to be off in its 119 least significant bit. 120 121 For further discussion and two alternative approaches, see the `ASPN cookbook 122 recipes for accurate floating point summation 123 <https://code.activestate.com/recipes/393090/>`_\. 124 125 126.. function:: gcd(a, b) 127 128 Return the greatest common divisor of the integers *a* and *b*. If either 129 *a* or *b* is nonzero, then the value of ``gcd(a, b)`` is the largest 130 positive integer that divides both *a* and *b*. ``gcd(0, 0)`` returns 131 ``0``. 132 133 .. versionadded:: 3.5 134 135 136.. function:: isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) 137 138 Return ``True`` if the values *a* and *b* are close to each other and 139 ``False`` otherwise. 140 141 Whether or not two values are considered close is determined according to 142 given absolute and relative tolerances. 143 144 *rel_tol* is the relative tolerance -- it is the maximum allowed difference 145 between *a* and *b*, relative to the larger absolute value of *a* or *b*. 146 For example, to set a tolerance of 5%, pass ``rel_tol=0.05``. The default 147 tolerance is ``1e-09``, which assures that the two values are the same 148 within about 9 decimal digits. *rel_tol* must be greater than zero. 149 150 *abs_tol* is the minimum absolute tolerance -- useful for comparisons near 151 zero. *abs_tol* must be at least zero. 152 153 If no errors occur, the result will be: 154 ``abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)``. 155 156 The IEEE 754 special values of ``NaN``, ``inf``, and ``-inf`` will be 157 handled according to IEEE rules. Specifically, ``NaN`` is not considered 158 close to any other value, including ``NaN``. ``inf`` and ``-inf`` are only 159 considered close to themselves. 160 161 .. versionadded:: 3.5 162 163 .. seealso:: 164 165 :pep:`485` -- A function for testing approximate equality 166 167 168.. function:: isfinite(x) 169 170 Return ``True`` if *x* is neither an infinity nor a NaN, and 171 ``False`` otherwise. (Note that ``0.0`` *is* considered finite.) 172 173 .. versionadded:: 3.2 174 175 176.. function:: isinf(x) 177 178 Return ``True`` if *x* is a positive or negative infinity, and 179 ``False`` otherwise. 180 181 182.. function:: isnan(x) 183 184 Return ``True`` if *x* is a NaN (not a number), and ``False`` otherwise. 185 186 187.. function:: isqrt(n) 188 189 Return the integer square root of the nonnegative integer *n*. This is the 190 floor of the exact square root of *n*, or equivalently the greatest integer 191 *a* such that *a*\ ² |nbsp| ≤ |nbsp| *n*. 192 193 For some applications, it may be more convenient to have the least integer 194 *a* such that *n* |nbsp| ≤ |nbsp| *a*\ ², or in other words the ceiling of 195 the exact square root of *n*. For positive *n*, this can be computed using 196 ``a = 1 + isqrt(n - 1)``. 197 198 .. versionadded:: 3.8 199 200 201.. function:: ldexp(x, i) 202 203 Return ``x * (2**i)``. This is essentially the inverse of function 204 :func:`frexp`. 205 206 207.. function:: modf(x) 208 209 Return the fractional and integer parts of *x*. Both results carry the sign 210 of *x* and are floats. 211 212 213.. function:: perm(n, k=None) 214 215 Return the number of ways to choose *k* items from *n* items 216 without repetition and with order. 217 218 Evaluates to ``n! / (n - k)!`` when ``k <= n`` and evaluates 219 to zero when ``k > n``. 220 221 If *k* is not specified or is None, then *k* defaults to *n* 222 and the function returns ``n!``. 223 224 Raises :exc:`TypeError` if either of the arguments are not integers. 225 Raises :exc:`ValueError` if either of the arguments are negative. 226 227 .. versionadded:: 3.8 228 229 230.. function:: prod(iterable, *, start=1) 231 232 Calculate the product of all the elements in the input *iterable*. 233 The default *start* value for the product is ``1``. 234 235 When the iterable is empty, return the start value. This function is 236 intended specifically for use with numeric values and may reject 237 non-numeric types. 238 239 .. versionadded:: 3.8 240 241 242.. function:: remainder(x, y) 243 244 Return the IEEE 754-style remainder of *x* with respect to *y*. For 245 finite *x* and finite nonzero *y*, this is the difference ``x - n*y``, 246 where ``n`` is the closest integer to the exact value of the quotient ``x / 247 y``. If ``x / y`` is exactly halfway between two consecutive integers, the 248 nearest *even* integer is used for ``n``. The remainder ``r = remainder(x, 249 y)`` thus always satisfies ``abs(r) <= 0.5 * abs(y)``. 250 251 Special cases follow IEEE 754: in particular, ``remainder(x, math.inf)`` is 252 *x* for any finite *x*, and ``remainder(x, 0)`` and 253 ``remainder(math.inf, x)`` raise :exc:`ValueError` for any non-NaN *x*. 254 If the result of the remainder operation is zero, that zero will have 255 the same sign as *x*. 256 257 On platforms using IEEE 754 binary floating-point, the result of this 258 operation is always exactly representable: no rounding error is introduced. 259 260 .. versionadded:: 3.7 261 262 263.. function:: trunc(x) 264 265 Return the :class:`~numbers.Real` value *x* truncated to an 266 :class:`~numbers.Integral` (usually an integer). Delegates to 267 :meth:`x.__trunc__() <object.__trunc__>`. 268 269 270Note that :func:`frexp` and :func:`modf` have a different call/return pattern 271than their C equivalents: they take a single argument and return a pair of 272values, rather than returning their second return value through an 'output 273parameter' (there is no such thing in Python). 274 275For the :func:`ceil`, :func:`floor`, and :func:`modf` functions, note that *all* 276floating-point numbers of sufficiently large magnitude are exact integers. 277Python floats typically carry no more than 53 bits of precision (the same as the 278platform C double type), in which case any float *x* with ``abs(x) >= 2**52`` 279necessarily has no fractional bits. 280 281 282Power and logarithmic functions 283------------------------------- 284 285.. function:: exp(x) 286 287 Return *e* raised to the power *x*, where *e* = 2.718281... is the base 288 of natural logarithms. This is usually more accurate than ``math.e ** x`` 289 or ``pow(math.e, x)``. 290 291 292.. function:: expm1(x) 293 294 Return *e* raised to the power *x*, minus 1. Here *e* is the base of natural 295 logarithms. For small floats *x*, the subtraction in ``exp(x) - 1`` 296 can result in a `significant loss of precision 297 <https://en.wikipedia.org/wiki/Loss_of_significance>`_\; the :func:`expm1` 298 function provides a way to compute this quantity to full precision:: 299 300 >>> from math import exp, expm1 301 >>> exp(1e-5) - 1 # gives result accurate to 11 places 302 1.0000050000069649e-05 303 >>> expm1(1e-5) # result accurate to full precision 304 1.0000050000166668e-05 305 306 .. versionadded:: 3.2 307 308 309.. function:: log(x[, base]) 310 311 With one argument, return the natural logarithm of *x* (to base *e*). 312 313 With two arguments, return the logarithm of *x* to the given *base*, 314 calculated as ``log(x)/log(base)``. 315 316 317.. function:: log1p(x) 318 319 Return the natural logarithm of *1+x* (base *e*). The 320 result is calculated in a way which is accurate for *x* near zero. 321 322 323.. function:: log2(x) 324 325 Return the base-2 logarithm of *x*. This is usually more accurate than 326 ``log(x, 2)``. 327 328 .. versionadded:: 3.3 329 330 .. seealso:: 331 332 :meth:`int.bit_length` returns the number of bits necessary to represent 333 an integer in binary, excluding the sign and leading zeros. 334 335 336.. function:: log10(x) 337 338 Return the base-10 logarithm of *x*. This is usually more accurate 339 than ``log(x, 10)``. 340 341 342.. function:: pow(x, y) 343 344 Return ``x`` raised to the power ``y``. Exceptional cases follow 345 Annex 'F' of the C99 standard as far as possible. In particular, 346 ``pow(1.0, x)`` and ``pow(x, 0.0)`` always return ``1.0``, even 347 when ``x`` is a zero or a NaN. If both ``x`` and ``y`` are finite, 348 ``x`` is negative, and ``y`` is not an integer then ``pow(x, y)`` 349 is undefined, and raises :exc:`ValueError`. 350 351 Unlike the built-in ``**`` operator, :func:`math.pow` converts both 352 its arguments to type :class:`float`. Use ``**`` or the built-in 353 :func:`pow` function for computing exact integer powers. 354 355 356.. function:: sqrt(x) 357 358 Return the square root of *x*. 359 360 361Trigonometric functions 362----------------------- 363 364.. function:: acos(x) 365 366 Return the arc cosine of *x*, in radians. 367 368 369.. function:: asin(x) 370 371 Return the arc sine of *x*, in radians. 372 373 374.. function:: atan(x) 375 376 Return the arc tangent of *x*, in radians. 377 378 379.. function:: atan2(y, x) 380 381 Return ``atan(y / x)``, in radians. The result is between ``-pi`` and ``pi``. 382 The vector in the plane from the origin to point ``(x, y)`` makes this angle 383 with the positive X axis. The point of :func:`atan2` is that the signs of both 384 inputs are known to it, so it can compute the correct quadrant for the angle. 385 For example, ``atan(1)`` and ``atan2(1, 1)`` are both ``pi/4``, but ``atan2(-1, 386 -1)`` is ``-3*pi/4``. 387 388 389.. function:: cos(x) 390 391 Return the cosine of *x* radians. 392 393 394.. function:: dist(p, q) 395 396 Return the Euclidean distance between two points *p* and *q*, each 397 given as a sequence (or iterable) of coordinates. The two points 398 must have the same dimension. 399 400 Roughly equivalent to:: 401 402 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) 403 404 .. versionadded:: 3.8 405 406 407.. function:: hypot(*coordinates) 408 409 Return the Euclidean norm, ``sqrt(sum(x**2 for x in coordinates))``. 410 This is the length of the vector from the origin to the point 411 given by the coordinates. 412 413 For a two dimensional point ``(x, y)``, this is equivalent to computing 414 the hypotenuse of a right triangle using the Pythagorean theorem, 415 ``sqrt(x*x + y*y)``. 416 417 .. versionchanged:: 3.8 418 Added support for n-dimensional points. Formerly, only the two 419 dimensional case was supported. 420 421 422.. function:: sin(x) 423 424 Return the sine of *x* radians. 425 426 427.. function:: tan(x) 428 429 Return the tangent of *x* radians. 430 431 432Angular conversion 433------------------ 434 435.. function:: degrees(x) 436 437 Convert angle *x* from radians to degrees. 438 439 440.. function:: radians(x) 441 442 Convert angle *x* from degrees to radians. 443 444 445Hyperbolic functions 446-------------------- 447 448`Hyperbolic functions <https://en.wikipedia.org/wiki/Hyperbolic_function>`_ 449are analogs of trigonometric functions that are based on hyperbolas 450instead of circles. 451 452.. function:: acosh(x) 453 454 Return the inverse hyperbolic cosine of *x*. 455 456 457.. function:: asinh(x) 458 459 Return the inverse hyperbolic sine of *x*. 460 461 462.. function:: atanh(x) 463 464 Return the inverse hyperbolic tangent of *x*. 465 466 467.. function:: cosh(x) 468 469 Return the hyperbolic cosine of *x*. 470 471 472.. function:: sinh(x) 473 474 Return the hyperbolic sine of *x*. 475 476 477.. function:: tanh(x) 478 479 Return the hyperbolic tangent of *x*. 480 481 482Special functions 483----------------- 484 485.. function:: erf(x) 486 487 Return the `error function <https://en.wikipedia.org/wiki/Error_function>`_ at 488 *x*. 489 490 The :func:`erf` function can be used to compute traditional statistical 491 functions such as the `cumulative standard normal distribution 492 <https://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function>`_:: 493 494 def phi(x): 495 'Cumulative distribution function for the standard normal distribution' 496 return (1.0 + erf(x / sqrt(2.0))) / 2.0 497 498 .. versionadded:: 3.2 499 500 501.. function:: erfc(x) 502 503 Return the complementary error function at *x*. The `complementary error 504 function <https://en.wikipedia.org/wiki/Error_function>`_ is defined as 505 ``1.0 - erf(x)``. It is used for large values of *x* where a subtraction 506 from one would cause a `loss of significance 507 <https://en.wikipedia.org/wiki/Loss_of_significance>`_\. 508 509 .. versionadded:: 3.2 510 511 512.. function:: gamma(x) 513 514 Return the `Gamma function <https://en.wikipedia.org/wiki/Gamma_function>`_ at 515 *x*. 516 517 .. versionadded:: 3.2 518 519 520.. function:: lgamma(x) 521 522 Return the natural logarithm of the absolute value of the Gamma 523 function at *x*. 524 525 .. versionadded:: 3.2 526 527 528Constants 529--------- 530 531.. data:: pi 532 533 The mathematical constant *π* = 3.141592..., to available precision. 534 535 536.. data:: e 537 538 The mathematical constant *e* = 2.718281..., to available precision. 539 540 541.. data:: tau 542 543 The mathematical constant *τ* = 6.283185..., to available precision. 544 Tau is a circle constant equal to 2\ *π*, the ratio of a circle's circumference to 545 its radius. To learn more about Tau, check out Vi Hart's video `Pi is (still) 546 Wrong <https://www.youtube.com/watch?v=jG7vhMMXagQ>`_, and start celebrating 547 `Tau day <https://tauday.com/>`_ by eating twice as much pie! 548 549 .. versionadded:: 3.6 550 551 552.. data:: inf 553 554 A floating-point positive infinity. (For negative infinity, use 555 ``-math.inf``.) Equivalent to the output of ``float('inf')``. 556 557 .. versionadded:: 3.5 558 559 560.. data:: nan 561 562 A floating-point "not a number" (NaN) value. Equivalent to the output of 563 ``float('nan')``. 564 565 .. versionadded:: 3.5 566 567 568.. impl-detail:: 569 570 The :mod:`math` module consists mostly of thin wrappers around the platform C 571 math library functions. Behavior in exceptional cases follows Annex F of 572 the C99 standard where appropriate. The current implementation will raise 573 :exc:`ValueError` for invalid operations like ``sqrt(-1.0)`` or ``log(0.0)`` 574 (where C99 Annex F recommends signaling invalid operation or divide-by-zero), 575 and :exc:`OverflowError` for results that overflow (for example, 576 ``exp(1000.0)``). A NaN will not be returned from any of the functions 577 above unless one or more of the input arguments was a NaN; in that case, 578 most functions will return a NaN, but (again following C99 Annex F) there 579 are some exceptions to this rule, for example ``pow(float('nan'), 0.0)`` or 580 ``hypot(float('nan'), float('inf'))``. 581 582 Note that Python makes no effort to distinguish signaling NaNs from 583 quiet NaNs, and behavior for signaling NaNs remains unspecified. 584 Typical behavior is to treat all NaNs as though they were quiet. 585 586 587.. seealso:: 588 589 Module :mod:`cmath` 590 Complex number versions of many of these functions. 591 592.. |nbsp| unicode:: 0xA0 593 :trim: 594