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)``.
325 If *x* is a finite nonzero number, then *m* is a float with
326 ``0.5 <= abs(m) < 1.0`` and an integer *e* is such that
327 ``x == m * 2**e`` exactly. Else, return ``(x, 0)``.
328 This is used to "pick apart" the internal representation of
329 a float in a portable way.
330
331 Note that :func:`frexp` has a different call/return pattern
332 than its C equivalents: it takes a single argument and return a pair of
333 values, rather than returning its second return value through an 'output
334 parameter' (there is no such thing in Python).
335
336 .. function:: isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
337
338 Return ``True`` if the values *a* and *b* are close to each other and
339 ``False`` otherwise.
340
341 Whether or not two values are considered close is determined according to
342 given absolute and relative tolerances. If no errors occur, the result will
343 be: ``abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)``.
344
345 *rel_tol* is the relative tolerance -- it is the maximum allowed difference
346 between *a* and *b*, relative to the larger absolute value of *a* or *b*.
347 For example, to set a tolerance of 5%, pass ``rel_tol=0.05``. The default
348 tolerance is ``1e-09``, which assures that the two values are the same
349 within about 9 decimal digits. *rel_tol* must be nonnegative and less
350 than ``1.0``.
351
352 *abs_tol* is the absolute tolerance; it defaults to ``0.0`` and it must be
353 nonnegative. When comparing ``x`` to ``0.0``, ``isclose(x, 0)`` is computed
354 as ``abs(x) <= rel_tol * abs(x)``, which is ``False`` for any nonzero ``x`` and
355 *rel_tol* less than ``1.0``. So add an appropriate positive *abs_tol* argument
356 to the call.
357
358 The IEEE 754 special values of ``NaN``, ``inf``, and ``-inf`` will be
359 handled according to IEEE rules. Specifically, ``NaN`` is not considered
360 close to any other value, including ``NaN``. ``inf`` and ``-inf`` are only
361 considered close to themselves.
362
363 .. versionadded:: 3.5
364
365 .. seealso::
366
367 :pep:`485` -- A function for testing approximate equality
368
369
370 .. function:: isfinite(x)
371
372 Return ``True`` if *x* is neither an infinity nor a NaN, and
373 ``False`` otherwise. (Note that ``0.0`` *is* considered finite.)
374
375 .. versionadded:: 3.2
376
377
378 .. function:: isinf(x)
379
380 Return ``True`` if *x* is a positive or negative infinity, and
381 ``False`` otherwise.
382
383
384 .. function:: isnan(x)
385
386 Return ``True`` if *x* is a NaN (not a number), and ``False`` otherwise.
387
388
389 .. function:: ldexp(x, i)
390
391 Return ``x * (2**i)``. This is essentially the inverse of function
392 :func:`frexp`.
393
394
395 .. function:: nextafter(x, y, steps=1)
396
397 Return the floating-point value *steps* steps after *x* towards *y*.
398
399 If *x* is equal to *y*, return *y*, unless *steps* is zero.
400
401 Examples:
402
403 * ``math.nextafter(x, math.inf)`` goes up: towards positive infinity.
404 * ``math.nextafter(x, -math.inf)`` goes down: towards minus infinity.
405 * ``math.nextafter(x, 0.0)`` goes towards zero.
406 * ``math.nextafter(x, math.copysign(math.inf, x))`` goes away from zero.
407
408 See also :func:`math.ulp`.
409
410 .. versionadded:: 3.9
411
412 .. versionchanged:: 3.12
413 Added the *steps* argument.
414
415
416 .. function:: ulp(x)
417
418 Return the value of the least significant bit of the float *x*:
419
420 * If *x* is a NaN (not a number), return *x*.
421 * If *x* is negative, return ``ulp(-x)``.
422 * If *x* is a positive infinity, return *x*.
423 * If *x* is equal to zero, return the smallest positive
424 *denormalized* representable float (smaller than the minimum positive
425 *normalized* float, :data:`sys.float_info.min <sys.float_info>`).
426 * If *x* is equal to the largest positive representable float,
427 return the value of the least significant bit of *x*, such that the first
428 float smaller than *x* is ``x - ulp(x)``.
429 * Otherwise (*x* is a positive finite number), return the value of the least
430 significant bit of *x*, such that the first float bigger than *x*
431 is ``x + ulp(x)``.
432
433 ULP stands for "Unit in the Last Place".
434
435 See also :func:`math.nextafter` and :data:`sys.float_info.epsilon
436 <sys.float_info>`.
437
438 .. versionadded:: 3.9
439
440
441 Power, exponential and logarithmic functions
442 --------------------------------------------
443
444 .. function:: cbrt(x)
445
446 Return the cube root of *x*.
447
448 .. versionadded:: 3.11
449
450
451 .. function:: exp(x)
452
453 Return *e* raised to the power *x*, where *e* = 2.718281... is the base
454 of natural logarithms. This is usually more accurate than ``math.e ** x``
455 or ``pow(math.e, x)``.
456
457
458 .. function:: exp2(x)
459
460 Return *2* raised to the power *x*.
461
462 .. versionadded:: 3.11
463
464
465 .. function:: expm1(x)
466
467 Return *e* raised to the power *x*, minus 1. Here *e* is the base of natural
468 logarithms. For small floats *x*, the subtraction in ``exp(x) - 1``
469 can result in a `significant loss of precision
470 <https://en.wikipedia.org/wiki/Loss_of_significance>`_\; the :func:`expm1`
471 function provides a way to compute this quantity to full precision:
472
473 >>> from math import exp, expm1
474 >>> exp(1e-5) - 1 # gives result accurate to 11 places
475 1.0000050000069649e-05
476 >>> expm1(1e-5) # result accurate to full precision
477 1.0000050000166668e-05
478
479 .. versionadded:: 3.2
480
481
482 .. function:: log(x[, base])
483
484 With one argument, return the natural logarithm of *x* (to base *e*).
485
486 With two arguments, return the logarithm of *x* to the given *base*,
487 calculated as ``log(x)/log(base)``.
488
489
490 .. function:: log1p(x)
491
492 Return the natural logarithm of *1+x* (base *e*). The
493 result is calculated in a way which is accurate for *x* near zero.
494
495
496 .. function:: log2(x)
497
498 Return the base-2 logarithm of *x*. This is usually more accurate than
499 ``log(x, 2)``.
500
501 .. versionadded:: 3.3
502
503 .. seealso::
504
505 :meth:`int.bit_length` returns the number of bits necessary to represent
506 an integer in binary, excluding the sign and leading zeros.
507
508
509 .. function:: log10(x)
510
511 Return the base-10 logarithm of *x*. This is usually more accurate
512 than ``log(x, 10)``.
513
514
515 .. function:: pow(x, y)
516
517 Return *x* raised to the power *y*. Exceptional cases follow
518 the IEEE 754 standard as far as possible. In particular,
519 ``pow(1.0, x)`` and ``pow(x, 0.0)`` always return ``1.0``, even
520 when *x* is a zero or a NaN. If both *x* and *y* are finite,
521 *x* is negative, and *y* is not an integer then ``pow(x, y)``
522 is undefined, and raises :exc:`ValueError`.
523
524 Unlike the built-in ``**`` operator, :func:`math.pow` converts both
525 its arguments to type :class:`float`. Use ``**`` or the built-in
526 :func:`pow` function for computing exact integer powers.
527
528 .. versionchanged:: 3.11
529 The special cases ``pow(0.0, -inf)`` and ``pow(-0.0, -inf)`` were
530 changed to return ``inf`` instead of raising :exc:`ValueError`,
531 for consistency with IEEE 754.
532
533
534 .. function:: sqrt(x)
535
536 Return the square root of *x*.
537
538
539 Summation and product functions
540 -------------------------------
541
542 .. function:: dist(p, q)
543
544 Return the Euclidean distance between two points *p* and *q*, each
545 given as a sequence (or iterable) of coordinates. The two points
546 must have the same dimension.
547
548 Roughly equivalent to::
549
550 sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
551
552 .. versionadded:: 3.8
553
554
555 .. function:: fsum(iterable)
556
557 Return an accurate floating-point sum of values in the iterable. Avoids
558 loss of precision by tracking multiple intermediate partial sums.
559
560 The algorithm's accuracy depends on IEEE-754 arithmetic guarantees and the
561 typical case where the rounding mode is half-even. On some non-Windows
562 builds, the underlying C library uses extended precision addition and may
563 occasionally double-round an intermediate sum causing it to be off in its
564 least significant bit.
565
566 For further discussion and two alternative approaches, see the `ASPN cookbook
567 recipes for accurate floating-point summation
568 <https://code.activestate.com/recipes/393090-binary-floating-point-summation-accurate-to-full-p/>`_\.
569
570
571 .. function:: hypot(*coordinates)
572
573 Return the Euclidean norm, ``sqrt(sum(x**2 for x in coordinates))``.
574 This is the length of the vector from the origin to the point
575 given by the coordinates.
576
577 For a two dimensional point ``(x, y)``, this is equivalent to computing
578 the hypotenuse of a right triangle using the Pythagorean theorem,
579 ``sqrt(x*x + y*y)``.
580
581 .. versionchanged:: 3.8
582 Added support for n-dimensional points. Formerly, only the two
583 dimensional case was supported.
584
585 .. versionchanged:: 3.10
586 Improved the algorithm's accuracy so that the maximum error is
587 under 1 ulp (unit in the last place). More typically, the result
588 is almost always correctly rounded to within 1/2 ulp.
589
590
591 .. function:: prod(iterable, *, start=1)
592
593 Calculate the product of all the elements in the input *iterable*.
594 The default *start* value for the product is ``1``.
595
596 When the iterable is empty, return the start value. This function is
597 intended specifically for use with numeric values and may reject
598 non-numeric types.
599
600 .. versionadded:: 3.8
601
602
603 .. function:: sumprod(p, q)
604
605 Return the sum of products of values from two iterables *p* and *q*.
606
607 Raises :exc:`ValueError` if the inputs do not have the same length.
608
609 Roughly equivalent to::
610
611 sum(map(operator.mul, p, q, strict=True))
612
613 For float and mixed int/float inputs, the intermediate products
614 and sums are computed with extended precision.
615
616 .. versionadded:: 3.12
617
618
619 Angular conversion
620 ------------------
621
622 .. function:: degrees(x)
623
624 Convert angle *x* from radians to degrees.
625
626
627 .. function:: radians(x)
628
629 Convert angle *x* from degrees to radians.
630
631
632 Trigonometric functions
633 -----------------------
634
635 .. function:: acos(x)
636
637 Return the arc cosine of *x*, in radians. The result is between ``0`` and
638 ``pi``.
639
640
641 .. function:: asin(x)
642
643 Return the arc sine of *x*, in radians. The result is between ``-pi/2`` and
644 ``pi/2``.
645
646
647 .. function:: atan(x)
648
649 Return the arc tangent of *x*, in radians. The result is between ``-pi/2`` and
650 ``pi/2``.
651
652
653 .. function:: atan2(y, x)
654
655 Return ``atan(y / x)``, in radians. The result is between ``-pi`` and ``pi``.
656 The vector in the plane from the origin to point ``(x, y)`` makes this angle
657 with the positive X axis. The point of :func:`atan2` is that the signs of both
658 inputs are known to it, so it can compute the correct quadrant for the angle.
659 For example, ``atan(1)`` and ``atan2(1, 1)`` are both ``pi/4``, but ``atan2(-1,
660 -1)`` is ``-3*pi/4``.
661
662
663 .. function:: cos(x)
664
665 Return the cosine of *x* radians.
666
667
668 .. function:: sin(x)
669
670 Return the sine of *x* radians.
671
672
673 .. function:: tan(x)
674
675 Return the tangent of *x* radians.
676
677
678 Hyperbolic functions
679 --------------------
680
681 `Hyperbolic functions <https://en.wikipedia.org/wiki/Hyperbolic_functions>`_
682 are analogs of trigonometric functions that are based on hyperbolas
683 instead of circles.
684
685 .. function:: acosh(x)
686
687 Return the inverse hyperbolic cosine of *x*.
688
689
690 .. function:: asinh(x)
691
692 Return the inverse hyperbolic sine of *x*.
693
694
695 .. function:: atanh(x)
696
697 Return the inverse hyperbolic tangent of *x*.
698
699
700 .. function:: cosh(x)
701
702 Return the hyperbolic cosine of *x*.
703
704
705 .. function:: sinh(x)
706
707 Return the hyperbolic sine of *x*.
708
709
710 .. function:: tanh(x)
711
712 Return the hyperbolic tangent of *x*.
713
714
715 Special functions
716 -----------------
717
718 .. function:: erf(x)
719
720 Return the `error function <https://en.wikipedia.org/wiki/Error_function>`_ at
721 *x*.
722
723 The :func:`erf` function can be used to compute traditional statistical
724 functions such as the `cumulative standard normal distribution
725 <https://en.wikipedia.org/wiki/Cumulative_distribution_function>`_::
726
727 def phi(x):
728 'Cumulative distribution function for the standard normal distribution'
729 return (1.0 + erf(x / sqrt(2.0))) / 2.0
730
731 .. versionadded:: 3.2
732
733
734 .. function:: erfc(x)
735
736 Return the complementary error function at *x*. The `complementary error
737 function <https://en.wikipedia.org/wiki/Error_function>`_ is defined as
738 ``1.0 - erf(x)``. It is used for large values of *x* where a subtraction
739 from one would cause a `loss of significance
740 <https://en.wikipedia.org/wiki/Loss_of_significance>`_\.
741
742 .. versionadded:: 3.2
743
744
745 .. function:: gamma(x)
746
747 Return the `Gamma function <https://en.wikipedia.org/wiki/Gamma_function>`_ at
748 *x*.
749
750 .. versionadded:: 3.2
751
752
753 .. function:: lgamma(x)
754
755 Return the natural logarithm of the absolute value of the Gamma
756 function at *x*.
757
758 .. versionadded:: 3.2
759
760
761 Constants
762 ---------
763
764 .. data:: pi
765
766 The mathematical constant *π* = 3.141592..., to available precision.
767
768
769 .. data:: e
770
771 The mathematical constant *e* = 2.718281..., to available precision.
772
773
774 .. data:: tau
775
776 The mathematical constant *τ* = 6.283185..., to available precision.
777 Tau is a circle constant equal to 2\ *π*, the ratio of a circle's circumference to
778 its radius. To learn more about Tau, check out Vi Hart's video `Pi is (still)
779 Wrong <https://vimeo.com/147792667>`_, and start celebrating
780 `Tau day <https://tauday.com/>`_ by eating twice as much pie!
781
782 .. versionadded:: 3.6
783
784
785 .. data:: inf
786
787 A floating-point positive infinity. (For negative infinity, use
788 ``-math.inf``.) Equivalent to the output of ``float('inf')``.
789
790 .. versionadded:: 3.5
791
792
793 .. data:: nan
794
795 A floating-point "not a number" (NaN) value. Equivalent to the output of
796 ``float('nan')``. Due to the requirements of the `IEEE-754 standard
797 <https://en.wikipedia.org/wiki/IEEE_754>`_, ``math.nan`` and ``float('nan')`` are
798 not considered to equal to any other numeric value, including themselves. To check
799 whether a number is a NaN, use the :func:`isnan` function to test
800 for NaNs instead of ``is`` or ``==``.
801 Example:
802
803 >>> import math
804 >>> math.nan == math.nan
805 False
806 >>> float('nan') == float('nan')
807 False
808 >>> math.isnan(math.nan)
809 True
810 >>> math.isnan(float('nan'))
811 True
812
813 .. versionadded:: 3.5
814
815 .. versionchanged:: 3.11
816 It is now always available.
817
818
819 .. impl-detail::
820
821 The :mod:`!math` module consists mostly of thin wrappers around the platform C
822 math library functions. Behavior in exceptional cases follows Annex F of
823 the C99 standard where appropriate. The current implementation will raise
824 :exc:`ValueError` for invalid operations like ``sqrt(-1.0)`` or ``log(0.0)``
825 (where C99 Annex F recommends signaling invalid operation or divide-by-zero),
826 and :exc:`OverflowError` for results that overflow (for example,
827 ``exp(1000.0)``). A NaN will not be returned from any of the functions
828 above unless one or more of the input arguments was a NaN; in that case,
829 most functions will return a NaN, but (again following C99 Annex F) there
830 are some exceptions to this rule, for example ``pow(float('nan'), 0.0)`` or
831 ``hypot(float('nan'), float('inf'))``.
832
833 Note that Python makes no effort to distinguish signaling NaNs from
834 quiet NaNs, and behavior for signaling NaNs remains unspecified.
835 Typical behavior is to treat all NaNs as though they were quiet.
836
837
838 .. seealso::
839
840 Module :mod:`cmath`
841 Complex number versions of many of these functions.
842
843 .. |nbsp| unicode:: 0xA0
844 :trim: