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