Debian Codegraph @

Doc/library/math.rst

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