blob: 244663eda9a9119ca168a706956b966aa94c31b2 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`math` --- Mathematical functions
2======================================
3
4.. module:: math
5 :synopsis: Mathematical functions (sin() etc.).
6
Łukasz Langa288234f2013-01-18 13:40:43 +01007.. testsetup::
8
9 from math import fsum
Georg Brandl116aa622007-08-15 14:28:22 +000010
11This module is always available. It provides access to the mathematical
12functions defined by the C standard.
13
14These functions cannot be used with complex numbers; use the functions of the
15same name from the :mod:`cmath` module if you require support for complex
16numbers. The distinction between functions which support complex numbers and
17those which don't is made since most users do not want to learn quite as much
18mathematics as required to understand complex numbers. Receiving an exception
19instead of a complex result allows earlier detection of the unexpected complex
20number used as a parameter, so that the programmer can determine how and why it
21was generated in the first place.
22
23The following functions are provided by this module. Except when explicitly
24noted otherwise, all return values are floats.
25
Georg Brandl116aa622007-08-15 14:28:22 +000026
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +000027Number-theoretic and representation functions
28---------------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +000029
30.. function:: ceil(x)
31
Georg Brandl2a033732008-04-05 17:37:09 +000032 Return the ceiling of *x*, the smallest integer greater than or equal to *x*.
33 If *x* is not a float, delegates to ``x.__ceil__()``, which should return an
Serhiy Storchakabfdcd432013-10-13 23:09:14 +030034 :class:`~numbers.Integral` value.
Christian Heimes072c0f12008-01-03 23:01:04 +000035
36
37.. function:: copysign(x, y)
38
Andrew Kuchling8cb1ec32014-02-16 11:11:25 -050039 Return a float with the magnitude (absolute value) of *x* but the sign of
40 *y*. On platforms that support signed zeros, ``copysign(1.0, -0.0)``
41 returns *-1.0*.
Christian Heimes072c0f12008-01-03 23:01:04 +000042
Georg Brandl116aa622007-08-15 14:28:22 +000043.. function:: fabs(x)
44
45 Return the absolute value of *x*.
46
Georg Brandlc28e1fa2008-06-10 19:20:26 +000047.. function:: factorial(x)
48
Benjamin Petersonfea6a942008-07-02 16:11:42 +000049 Return *x* factorial. Raises :exc:`ValueError` if *x* is not integral or
Georg Brandlc28e1fa2008-06-10 19:20:26 +000050 is negative.
Georg Brandl116aa622007-08-15 14:28:22 +000051
52.. function:: floor(x)
53
Georg Brandl2a033732008-04-05 17:37:09 +000054 Return the floor of *x*, the largest integer less than or equal to *x*.
55 If *x* is not a float, delegates to ``x.__floor__()``, which should return an
Serhiy Storchakabfdcd432013-10-13 23:09:14 +030056 :class:`~numbers.Integral` value.
Georg Brandl116aa622007-08-15 14:28:22 +000057
58
59.. function:: fmod(x, y)
60
61 Return ``fmod(x, y)``, as defined by the platform C library. Note that the
62 Python expression ``x % y`` may not return the same result. The intent of the C
63 standard is that ``fmod(x, y)`` be exactly (mathematically; to infinite
64 precision) equal to ``x - n*y`` for some integer *n* such that the result has
65 the same sign as *x* and magnitude less than ``abs(y)``. Python's ``x % y``
66 returns a result with the sign of *y* instead, and may not be exactly computable
67 for float arguments. For example, ``fmod(-1e-100, 1e100)`` is ``-1e-100``, but
68 the result of Python's ``-1e-100 % 1e100`` is ``1e100-1e-100``, which cannot be
69 represented exactly as a float, and rounds to the surprising ``1e100``. For
70 this reason, function :func:`fmod` is generally preferred when working with
71 floats, while Python's ``x % y`` is preferred when working with integers.
72
73
74.. function:: frexp(x)
75
76 Return the mantissa and exponent of *x* as the pair ``(m, e)``. *m* is a float
77 and *e* is an integer such that ``x == m * 2**e`` exactly. If *x* is zero,
78 returns ``(0.0, 0)``, otherwise ``0.5 <= abs(m) < 1``. This is used to "pick
79 apart" the internal representation of a float in a portable way.
80
81
Mark Dickinsonaa7633a2008-08-01 08:16:13 +000082.. function:: fsum(iterable)
83
84 Return an accurate floating point sum of values in the iterable. Avoids
Raymond Hettingerf3936f82009-02-19 05:48:05 +000085 loss of precision by tracking multiple intermediate partial sums::
Mark Dickinsonaa7633a2008-08-01 08:16:13 +000086
Raymond Hettingerf3936f82009-02-19 05:48:05 +000087 >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
Mark Dickinson5a55b612009-06-28 20:59:42 +000088 0.9999999999999999
Raymond Hettingerf3936f82009-02-19 05:48:05 +000089 >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
90 1.0
Mark Dickinsonaa7633a2008-08-01 08:16:13 +000091
Raymond Hettingerf3936f82009-02-19 05:48:05 +000092 The algorithm's accuracy depends on IEEE-754 arithmetic guarantees and the
93 typical case where the rounding mode is half-even. On some non-Windows
94 builds, the underlying C library uses extended precision addition and may
95 occasionally double-round an intermediate sum causing it to be off in its
96 least significant bit.
Mark Dickinsonaa7633a2008-08-01 08:16:13 +000097
Raymond Hettinger477be822009-02-19 06:44:30 +000098 For further discussion and two alternative approaches, see the `ASPN cookbook
99 recipes for accurate floating point summation
100 <http://code.activestate.com/recipes/393090/>`_\.
101
Mark Dickinsonaa7633a2008-08-01 08:16:13 +0000102
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300103.. function:: gcd(a, b)
104
105 Return the greatest common divisor of the integers *a* and *b*. If either
106 *a* or *b* is nonzero, then the value of ``gcd(a, b)`` is the largest
107 positive integer that divides both *a* and *b*. ``gcd(0, 0)`` returns
108 ``0``.
109
Benjamin Petersone960d182015-05-12 17:24:17 -0400110 .. versionadded:: 3.5
111
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +0300112
Tal Einatd5519ed2015-05-31 22:05:00 +0300113.. function:: isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
114
115 Return ``True`` if the values *a* and *b* are close to each other and
116 ``False`` otherwise.
117
118 Whether or not two values are considered close is determined according to
119 given absolute and relative tolerances.
120
121 *rel_tol* is the relative tolerance -- it is the maximum allowed difference
122 between *a* and *b*, relative to the larger absolute value of *a* or *b*.
123 For example, to set a tolerance of 5%, pass ``rel_tol=0.05``. The default
124 tolerance is ``1e-09``, which assures that the two values are the same
125 within about 9 decimal digits. *rel_tol* must be greater than zero.
126
127 *abs_tol* is the minimum absolute tolerance -- useful for comparisons near
128 zero. *abs_tol* must be at least zero.
129
130 If no errors occur, the result will be:
131 ``abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)``.
132
133 The IEEE 754 special values of ``NaN``, ``inf``, and ``-inf`` will be
134 handled according to IEEE rules. Specifically, ``NaN`` is not considered
135 close to any other value, including ``NaN``. ``inf`` and ``-inf`` are only
136 considered close to themselves.
137
138 .. versionadded:: 3.5
139
140 .. seealso::
141
142 :pep:`485` -- A function for testing approximate equality
143
144
Mark Dickinson8e0c9962010-07-11 17:38:24 +0000145.. function:: isfinite(x)
146
147 Return ``True`` if *x* is neither an infinity nor a NaN, and
148 ``False`` otherwise. (Note that ``0.0`` *is* considered finite.)
149
Mark Dickinsonc7622422010-07-11 19:47:37 +0000150 .. versionadded:: 3.2
151
Mark Dickinson8e0c9962010-07-11 17:38:24 +0000152
Christian Heimes072c0f12008-01-03 23:01:04 +0000153.. function:: isinf(x)
154
Mark Dickinsonc7622422010-07-11 19:47:37 +0000155 Return ``True`` if *x* is a positive or negative infinity, and
156 ``False`` otherwise.
Christian Heimes072c0f12008-01-03 23:01:04 +0000157
Christian Heimes072c0f12008-01-03 23:01:04 +0000158
159.. function:: isnan(x)
160
Mark Dickinsonc7622422010-07-11 19:47:37 +0000161 Return ``True`` if *x* is a NaN (not a number), and ``False`` otherwise.
Christian Heimes072c0f12008-01-03 23:01:04 +0000162
Christian Heimes072c0f12008-01-03 23:01:04 +0000163
Georg Brandl116aa622007-08-15 14:28:22 +0000164.. function:: ldexp(x, i)
165
166 Return ``x * (2**i)``. This is essentially the inverse of function
167 :func:`frexp`.
168
169
170.. function:: modf(x)
171
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000172 Return the fractional and integer parts of *x*. Both results carry the sign
173 of *x* and are floats.
Georg Brandl116aa622007-08-15 14:28:22 +0000174
Christian Heimes400adb02008-02-01 08:12:03 +0000175
176.. function:: trunc(x)
177
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300178 Return the :class:`~numbers.Real` value *x* truncated to an
179 :class:`~numbers.Integral` (usually an integer). Delegates to
180 ``x.__trunc__()``.
Christian Heimes400adb02008-02-01 08:12:03 +0000181
Christian Heimes400adb02008-02-01 08:12:03 +0000182
Georg Brandl116aa622007-08-15 14:28:22 +0000183Note that :func:`frexp` and :func:`modf` have a different call/return pattern
184than their C equivalents: they take a single argument and return a pair of
185values, rather than returning their second return value through an 'output
186parameter' (there is no such thing in Python).
187
188For the :func:`ceil`, :func:`floor`, and :func:`modf` functions, note that *all*
189floating-point numbers of sufficiently large magnitude are exact integers.
190Python floats typically carry no more than 53 bits of precision (the same as the
191platform C double type), in which case any float *x* with ``abs(x) >= 2**52``
192necessarily has no fractional bits.
193
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000194
195Power and logarithmic functions
196-------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000197
Georg Brandl116aa622007-08-15 14:28:22 +0000198.. function:: exp(x)
199
200 Return ``e**x``.
201
202
Mark Dickinson664b5112009-12-16 20:23:42 +0000203.. function:: expm1(x)
204
Raymond Hettinger1081d482011-03-31 12:04:53 -0700205 Return ``e**x - 1``. For small floats *x*, the subtraction in ``exp(x) - 1``
206 can result in a `significant loss of precision
207 <http://en.wikipedia.org/wiki/Loss_of_significance>`_\; the :func:`expm1`
208 function provides a way to compute this quantity to full precision::
Mark Dickinson664b5112009-12-16 20:23:42 +0000209
210 >>> from math import exp, expm1
211 >>> exp(1e-5) - 1 # gives result accurate to 11 places
212 1.0000050000069649e-05
213 >>> expm1(1e-5) # result accurate to full precision
214 1.0000050000166668e-05
215
Mark Dickinson45f992a2009-12-19 11:20:49 +0000216 .. versionadded:: 3.2
217
Mark Dickinson664b5112009-12-16 20:23:42 +0000218
Georg Brandl116aa622007-08-15 14:28:22 +0000219.. function:: log(x[, base])
220
Georg Brandla6053b42009-09-01 08:11:14 +0000221 With one argument, return the natural logarithm of *x* (to base *e*).
222
223 With two arguments, return the logarithm of *x* to the given *base*,
224 calculated as ``log(x)/log(base)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000225
Georg Brandl116aa622007-08-15 14:28:22 +0000226
Christian Heimes53876d92008-04-19 00:31:39 +0000227.. function:: log1p(x)
228
229 Return the natural logarithm of *1+x* (base *e*). The
230 result is calculated in a way which is accurate for *x* near zero.
231
Christian Heimes53876d92008-04-19 00:31:39 +0000232
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200233.. function:: log2(x)
234
Benjamin Petersoneaee1382011-05-08 19:48:08 -0500235 Return the base-2 logarithm of *x*. This is usually more accurate than
236 ``log(x, 2)``.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200237
238 .. versionadded:: 3.3
239
Victor Stinner9415afc2011-09-21 03:35:18 +0200240 .. seealso::
241
242 :meth:`int.bit_length` returns the number of bits necessary to represent
243 an integer in binary, excluding the sign and leading zeros.
244
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200245
Georg Brandl116aa622007-08-15 14:28:22 +0000246.. function:: log10(x)
247
Georg Brandla6053b42009-09-01 08:11:14 +0000248 Return the base-10 logarithm of *x*. This is usually more accurate
249 than ``log(x, 10)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251
252.. function:: pow(x, y)
253
Christian Heimesa342c012008-04-20 21:01:16 +0000254 Return ``x`` raised to the power ``y``. Exceptional cases follow
255 Annex 'F' of the C99 standard as far as possible. In particular,
256 ``pow(1.0, x)`` and ``pow(x, 0.0)`` always return ``1.0``, even
257 when ``x`` is a zero or a NaN. If both ``x`` and ``y`` are finite,
258 ``x`` is negative, and ``y`` is not an integer then ``pow(x, y)``
259 is undefined, and raises :exc:`ValueError`.
Christian Heimes53876d92008-04-19 00:31:39 +0000260
Ezio Melotti739d5492013-02-23 04:53:44 +0200261 Unlike the built-in ``**`` operator, :func:`math.pow` converts both
262 its arguments to type :class:`float`. Use ``**`` or the built-in
263 :func:`pow` function for computing exact integer powers.
264
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266.. function:: sqrt(x)
267
268 Return the square root of *x*.
269
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000270Trigonometric functions
271-----------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000272
273
274.. function:: acos(x)
275
276 Return the arc cosine of *x*, in radians.
277
278
279.. function:: asin(x)
280
281 Return the arc sine of *x*, in radians.
282
283
284.. function:: atan(x)
285
286 Return the arc tangent of *x*, in radians.
287
288
289.. function:: atan2(y, x)
290
291 Return ``atan(y / x)``, in radians. The result is between ``-pi`` and ``pi``.
292 The vector in the plane from the origin to point ``(x, y)`` makes this angle
293 with the positive X axis. The point of :func:`atan2` is that the signs of both
294 inputs are known to it, so it can compute the correct quadrant for the angle.
Mark Dickinson603b7532010-04-06 19:55:03 +0000295 For example, ``atan(1)`` and ``atan2(1, 1)`` are both ``pi/4``, but ``atan2(-1,
Georg Brandl116aa622007-08-15 14:28:22 +0000296 -1)`` is ``-3*pi/4``.
297
298
299.. function:: cos(x)
300
301 Return the cosine of *x* radians.
302
303
304.. function:: hypot(x, y)
305
306 Return the Euclidean norm, ``sqrt(x*x + y*y)``. This is the length of the vector
307 from the origin to point ``(x, y)``.
308
309
310.. function:: sin(x)
311
312 Return the sine of *x* radians.
313
314
315.. function:: tan(x)
316
317 Return the tangent of *x* radians.
318
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000319Angular conversion
320------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000321
322
323.. function:: degrees(x)
324
Benjamin Peterson19a3f172015-05-12 19:15:53 -0400325 Convert angle *x* from radians to degrees.
Georg Brandl116aa622007-08-15 14:28:22 +0000326
327
328.. function:: radians(x)
329
Benjamin Peterson19a3f172015-05-12 19:15:53 -0400330 Convert angle *x* from degrees to radians.
Georg Brandl116aa622007-08-15 14:28:22 +0000331
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000332Hyperbolic functions
333--------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000334
Raymond Hettinger1081d482011-03-31 12:04:53 -0700335`Hyperbolic functions <http://en.wikipedia.org/wiki/Hyperbolic_function>`_
336are analogs of trigonometric functions that are based on hyperbolas
337instead of circles.
Georg Brandl116aa622007-08-15 14:28:22 +0000338
Christian Heimesa342c012008-04-20 21:01:16 +0000339.. function:: acosh(x)
340
341 Return the inverse hyperbolic cosine of *x*.
342
Christian Heimesa342c012008-04-20 21:01:16 +0000343
344.. function:: asinh(x)
345
346 Return the inverse hyperbolic sine of *x*.
347
Christian Heimesa342c012008-04-20 21:01:16 +0000348
349.. function:: atanh(x)
350
351 Return the inverse hyperbolic tangent of *x*.
352
Christian Heimesa342c012008-04-20 21:01:16 +0000353
Georg Brandl116aa622007-08-15 14:28:22 +0000354.. function:: cosh(x)
355
356 Return the hyperbolic cosine of *x*.
357
358
359.. function:: sinh(x)
360
361 Return the hyperbolic sine of *x*.
362
363
364.. function:: tanh(x)
365
366 Return the hyperbolic tangent of *x*.
367
Christian Heimes53876d92008-04-19 00:31:39 +0000368
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000369Special functions
370-----------------
371
Mark Dickinson45f992a2009-12-19 11:20:49 +0000372.. function:: erf(x)
373
Raymond Hettinger1081d482011-03-31 12:04:53 -0700374 Return the `error function <http://en.wikipedia.org/wiki/Error_function>`_ at
375 *x*.
376
377 The :func:`erf` function can be used to compute traditional statistical
378 functions such as the `cumulative standard normal distribution
379 <http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function>`_::
380
381 def phi(x):
382 'Cumulative distribution function for the standard normal distribution'
383 return (1.0 + erf(x / sqrt(2.0))) / 2.0
Mark Dickinson45f992a2009-12-19 11:20:49 +0000384
385 .. versionadded:: 3.2
386
387
388.. function:: erfc(x)
389
Raymond Hettinger1081d482011-03-31 12:04:53 -0700390 Return the complementary error function at *x*. The `complementary error
391 function <http://en.wikipedia.org/wiki/Error_function>`_ is defined as
Raymond Hettinger12e6c252011-03-31 13:59:24 -0700392 ``1.0 - erf(x)``. It is used for large values of *x* where a subtraction
393 from one would cause a `loss of significance
Raymond Hettinger1081d482011-03-31 12:04:53 -0700394 <http://en.wikipedia.org/wiki/Loss_of_significance>`_\.
Mark Dickinson45f992a2009-12-19 11:20:49 +0000395
396 .. versionadded:: 3.2
397
398
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000399.. function:: gamma(x)
400
Raymond Hettinger12e6c252011-03-31 13:59:24 -0700401 Return the `Gamma function <http://en.wikipedia.org/wiki/Gamma_function>`_ at
402 *x*.
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000403
Mark Dickinson56e09662009-10-01 16:13:29 +0000404 .. versionadded:: 3.2
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000405
406
Mark Dickinson05d2e082009-12-11 20:17:17 +0000407.. function:: lgamma(x)
408
409 Return the natural logarithm of the absolute value of the Gamma
410 function at *x*.
411
Mark Dickinson45f992a2009-12-19 11:20:49 +0000412 .. versionadded:: 3.2
Mark Dickinson05d2e082009-12-11 20:17:17 +0000413
414
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000415Constants
Mark Dickinson60fe6b02009-06-02 12:53:15 +0000416---------
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418.. data:: pi
419
Mark Dickinson603b7532010-04-06 19:55:03 +0000420 The mathematical constant π = 3.141592..., to available precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000421
422
423.. data:: e
424
Mark Dickinson603b7532010-04-06 19:55:03 +0000425 The mathematical constant e = 2.718281..., to available precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000426
Christian Heimes53876d92008-04-19 00:31:39 +0000427
Mark Dickinsona5d0c7c2015-01-11 11:55:29 +0000428.. data:: inf
429
430 A floating-point positive infinity. (For negative infinity, use
431 ``-math.inf``.) Equivalent to the output of ``float('inf')``.
432
433 .. versionadded:: 3.5
434
435
436.. data:: nan
437
438 A floating-point "not a number" (NaN) value. Equivalent to the output of
439 ``float('nan')``.
440
441 .. versionadded:: 3.5
442
443
Georg Brandl495f7b52009-10-27 15:28:25 +0000444.. impl-detail::
Georg Brandl116aa622007-08-15 14:28:22 +0000445
446 The :mod:`math` module consists mostly of thin wrappers around the platform C
Mark Dickinson603b7532010-04-06 19:55:03 +0000447 math library functions. Behavior in exceptional cases follows Annex F of
448 the C99 standard where appropriate. The current implementation will raise
449 :exc:`ValueError` for invalid operations like ``sqrt(-1.0)`` or ``log(0.0)``
450 (where C99 Annex F recommends signaling invalid operation or divide-by-zero),
451 and :exc:`OverflowError` for results that overflow (for example,
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000452 ``exp(1000.0)``). A NaN will not be returned from any of the functions
453 above unless one or more of the input arguments was a NaN; in that case,
454 most functions will return a NaN, but (again following C99 Annex F) there
Mark Dickinson603b7532010-04-06 19:55:03 +0000455 are some exceptions to this rule, for example ``pow(float('nan'), 0.0)`` or
456 ``hypot(float('nan'), float('inf'))``.
Georg Brandl116aa622007-08-15 14:28:22 +0000457
Mark Dickinson42dfeec2010-04-06 22:13:37 +0000458 Note that Python makes no effort to distinguish signaling NaNs from
459 quiet NaNs, and behavior for signaling NaNs remains unspecified.
460 Typical behavior is to treat all NaNs as though they were quiet.
Christian Heimes53876d92008-04-19 00:31:39 +0000461
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463.. seealso::
464
465 Module :mod:`cmath`
466 Complex number versions of many of these functions.