blob: 3c4167209540fded656f894ef6e012b91f3eafe4 [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
Larry Hastings3732ed22014-03-15 21:13:56 -070039 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*.
Georg Brandl116aa622007-08-15 14:28:22 +000042
43.. 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
Mark Dickinson8e0c9962010-07-11 17:38:24 +0000103.. function:: isfinite(x)
104
105 Return ``True`` if *x* is neither an infinity nor a NaN, and
106 ``False`` otherwise. (Note that ``0.0`` *is* considered finite.)
107
Mark Dickinsonc7622422010-07-11 19:47:37 +0000108 .. versionadded:: 3.2
109
Mark Dickinson8e0c9962010-07-11 17:38:24 +0000110
Christian Heimes072c0f12008-01-03 23:01:04 +0000111.. function:: isinf(x)
112
Mark Dickinsonc7622422010-07-11 19:47:37 +0000113 Return ``True`` if *x* is a positive or negative infinity, and
114 ``False`` otherwise.
Christian Heimes072c0f12008-01-03 23:01:04 +0000115
Christian Heimes072c0f12008-01-03 23:01:04 +0000116
117.. function:: isnan(x)
118
Mark Dickinsonc7622422010-07-11 19:47:37 +0000119 Return ``True`` if *x* is a NaN (not a number), and ``False`` otherwise.
Christian Heimes072c0f12008-01-03 23:01:04 +0000120
Christian Heimes072c0f12008-01-03 23:01:04 +0000121
Georg Brandl116aa622007-08-15 14:28:22 +0000122.. function:: ldexp(x, i)
123
124 Return ``x * (2**i)``. This is essentially the inverse of function
125 :func:`frexp`.
126
127
128.. function:: modf(x)
129
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000130 Return the fractional and integer parts of *x*. Both results carry the sign
131 of *x* and are floats.
Georg Brandl116aa622007-08-15 14:28:22 +0000132
Christian Heimes400adb02008-02-01 08:12:03 +0000133
134.. function:: trunc(x)
135
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300136 Return the :class:`~numbers.Real` value *x* truncated to an
137 :class:`~numbers.Integral` (usually an integer). Delegates to
138 ``x.__trunc__()``.
Christian Heimes400adb02008-02-01 08:12:03 +0000139
Christian Heimes400adb02008-02-01 08:12:03 +0000140
Georg Brandl116aa622007-08-15 14:28:22 +0000141Note that :func:`frexp` and :func:`modf` have a different call/return pattern
142than their C equivalents: they take a single argument and return a pair of
143values, rather than returning their second return value through an 'output
144parameter' (there is no such thing in Python).
145
146For the :func:`ceil`, :func:`floor`, and :func:`modf` functions, note that *all*
147floating-point numbers of sufficiently large magnitude are exact integers.
148Python floats typically carry no more than 53 bits of precision (the same as the
149platform C double type), in which case any float *x* with ``abs(x) >= 2**52``
150necessarily has no fractional bits.
151
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000152
153Power and logarithmic functions
154-------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Georg Brandl116aa622007-08-15 14:28:22 +0000156.. function:: exp(x)
157
158 Return ``e**x``.
159
160
Mark Dickinson664b5112009-12-16 20:23:42 +0000161.. function:: expm1(x)
162
Raymond Hettinger1081d482011-03-31 12:04:53 -0700163 Return ``e**x - 1``. For small floats *x*, the subtraction in ``exp(x) - 1``
164 can result in a `significant loss of precision
165 <http://en.wikipedia.org/wiki/Loss_of_significance>`_\; the :func:`expm1`
166 function provides a way to compute this quantity to full precision::
Mark Dickinson664b5112009-12-16 20:23:42 +0000167
168 >>> from math import exp, expm1
169 >>> exp(1e-5) - 1 # gives result accurate to 11 places
170 1.0000050000069649e-05
171 >>> expm1(1e-5) # result accurate to full precision
172 1.0000050000166668e-05
173
Mark Dickinson45f992a2009-12-19 11:20:49 +0000174 .. versionadded:: 3.2
175
Mark Dickinson664b5112009-12-16 20:23:42 +0000176
Georg Brandl116aa622007-08-15 14:28:22 +0000177.. function:: log(x[, base])
178
Georg Brandla6053b42009-09-01 08:11:14 +0000179 With one argument, return the natural logarithm of *x* (to base *e*).
180
181 With two arguments, return the logarithm of *x* to the given *base*,
182 calculated as ``log(x)/log(base)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000183
Georg Brandl116aa622007-08-15 14:28:22 +0000184
Christian Heimes53876d92008-04-19 00:31:39 +0000185.. function:: log1p(x)
186
187 Return the natural logarithm of *1+x* (base *e*). The
188 result is calculated in a way which is accurate for *x* near zero.
189
Christian Heimes53876d92008-04-19 00:31:39 +0000190
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200191.. function:: log2(x)
192
Benjamin Petersoneaee1382011-05-08 19:48:08 -0500193 Return the base-2 logarithm of *x*. This is usually more accurate than
194 ``log(x, 2)``.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200195
196 .. versionadded:: 3.3
197
Victor Stinner9415afc2011-09-21 03:35:18 +0200198 .. seealso::
199
200 :meth:`int.bit_length` returns the number of bits necessary to represent
201 an integer in binary, excluding the sign and leading zeros.
202
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200203
Georg Brandl116aa622007-08-15 14:28:22 +0000204.. function:: log10(x)
205
Georg Brandla6053b42009-09-01 08:11:14 +0000206 Return the base-10 logarithm of *x*. This is usually more accurate
207 than ``log(x, 10)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209
210.. function:: pow(x, y)
211
Christian Heimesa342c012008-04-20 21:01:16 +0000212 Return ``x`` raised to the power ``y``. Exceptional cases follow
213 Annex 'F' of the C99 standard as far as possible. In particular,
214 ``pow(1.0, x)`` and ``pow(x, 0.0)`` always return ``1.0``, even
215 when ``x`` is a zero or a NaN. If both ``x`` and ``y`` are finite,
216 ``x`` is negative, and ``y`` is not an integer then ``pow(x, y)``
217 is undefined, and raises :exc:`ValueError`.
Christian Heimes53876d92008-04-19 00:31:39 +0000218
Ezio Melotti739d5492013-02-23 04:53:44 +0200219 Unlike the built-in ``**`` operator, :func:`math.pow` converts both
220 its arguments to type :class:`float`. Use ``**`` or the built-in
221 :func:`pow` function for computing exact integer powers.
222
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224.. function:: sqrt(x)
225
226 Return the square root of *x*.
227
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000228Trigonometric functions
229-----------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231
232.. function:: acos(x)
233
234 Return the arc cosine of *x*, in radians.
235
236
237.. function:: asin(x)
238
239 Return the arc sine of *x*, in radians.
240
241
242.. function:: atan(x)
243
244 Return the arc tangent of *x*, in radians.
245
246
247.. function:: atan2(y, x)
248
249 Return ``atan(y / x)``, in radians. The result is between ``-pi`` and ``pi``.
250 The vector in the plane from the origin to point ``(x, y)`` makes this angle
251 with the positive X axis. The point of :func:`atan2` is that the signs of both
252 inputs are known to it, so it can compute the correct quadrant for the angle.
Mark Dickinson603b7532010-04-06 19:55:03 +0000253 For example, ``atan(1)`` and ``atan2(1, 1)`` are both ``pi/4``, but ``atan2(-1,
Georg Brandl116aa622007-08-15 14:28:22 +0000254 -1)`` is ``-3*pi/4``.
255
256
257.. function:: cos(x)
258
259 Return the cosine of *x* radians.
260
261
262.. function:: hypot(x, y)
263
264 Return the Euclidean norm, ``sqrt(x*x + y*y)``. This is the length of the vector
265 from the origin to point ``(x, y)``.
266
267
268.. function:: sin(x)
269
270 Return the sine of *x* radians.
271
272
273.. function:: tan(x)
274
275 Return the tangent of *x* radians.
276
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000277Angular conversion
278------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280
281.. function:: degrees(x)
282
283 Converts angle *x* from radians to degrees.
284
285
286.. function:: radians(x)
287
288 Converts angle *x* from degrees to radians.
289
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000290Hyperbolic functions
291--------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000292
Raymond Hettinger1081d482011-03-31 12:04:53 -0700293`Hyperbolic functions <http://en.wikipedia.org/wiki/Hyperbolic_function>`_
294are analogs of trigonometric functions that are based on hyperbolas
295instead of circles.
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Christian Heimesa342c012008-04-20 21:01:16 +0000297.. function:: acosh(x)
298
299 Return the inverse hyperbolic cosine of *x*.
300
Christian Heimesa342c012008-04-20 21:01:16 +0000301
302.. function:: asinh(x)
303
304 Return the inverse hyperbolic sine of *x*.
305
Christian Heimesa342c012008-04-20 21:01:16 +0000306
307.. function:: atanh(x)
308
309 Return the inverse hyperbolic tangent of *x*.
310
Christian Heimesa342c012008-04-20 21:01:16 +0000311
Georg Brandl116aa622007-08-15 14:28:22 +0000312.. function:: cosh(x)
313
314 Return the hyperbolic cosine of *x*.
315
316
317.. function:: sinh(x)
318
319 Return the hyperbolic sine of *x*.
320
321
322.. function:: tanh(x)
323
324 Return the hyperbolic tangent of *x*.
325
Christian Heimes53876d92008-04-19 00:31:39 +0000326
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000327Special functions
328-----------------
329
Mark Dickinson45f992a2009-12-19 11:20:49 +0000330.. function:: erf(x)
331
Raymond Hettinger1081d482011-03-31 12:04:53 -0700332 Return the `error function <http://en.wikipedia.org/wiki/Error_function>`_ at
333 *x*.
334
335 The :func:`erf` function can be used to compute traditional statistical
336 functions such as the `cumulative standard normal distribution
337 <http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function>`_::
338
339 def phi(x):
340 'Cumulative distribution function for the standard normal distribution'
341 return (1.0 + erf(x / sqrt(2.0))) / 2.0
Mark Dickinson45f992a2009-12-19 11:20:49 +0000342
343 .. versionadded:: 3.2
344
345
346.. function:: erfc(x)
347
Raymond Hettinger1081d482011-03-31 12:04:53 -0700348 Return the complementary error function at *x*. The `complementary error
349 function <http://en.wikipedia.org/wiki/Error_function>`_ is defined as
Raymond Hettinger12e6c252011-03-31 13:59:24 -0700350 ``1.0 - erf(x)``. It is used for large values of *x* where a subtraction
351 from one would cause a `loss of significance
Raymond Hettinger1081d482011-03-31 12:04:53 -0700352 <http://en.wikipedia.org/wiki/Loss_of_significance>`_\.
Mark Dickinson45f992a2009-12-19 11:20:49 +0000353
354 .. versionadded:: 3.2
355
356
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000357.. function:: gamma(x)
358
Raymond Hettinger12e6c252011-03-31 13:59:24 -0700359 Return the `Gamma function <http://en.wikipedia.org/wiki/Gamma_function>`_ at
360 *x*.
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000361
Mark Dickinson56e09662009-10-01 16:13:29 +0000362 .. versionadded:: 3.2
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000363
364
Mark Dickinson05d2e082009-12-11 20:17:17 +0000365.. function:: lgamma(x)
366
367 Return the natural logarithm of the absolute value of the Gamma
368 function at *x*.
369
Mark Dickinson45f992a2009-12-19 11:20:49 +0000370 .. versionadded:: 3.2
Mark Dickinson05d2e082009-12-11 20:17:17 +0000371
372
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000373Constants
Mark Dickinson60fe6b02009-06-02 12:53:15 +0000374---------
Georg Brandl116aa622007-08-15 14:28:22 +0000375
376.. data:: pi
377
Mark Dickinson603b7532010-04-06 19:55:03 +0000378 The mathematical constant π = 3.141592..., to available precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380
381.. data:: e
382
Mark Dickinson603b7532010-04-06 19:55:03 +0000383 The mathematical constant e = 2.718281..., to available precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000384
Christian Heimes53876d92008-04-19 00:31:39 +0000385
Georg Brandl495f7b52009-10-27 15:28:25 +0000386.. impl-detail::
Georg Brandl116aa622007-08-15 14:28:22 +0000387
388 The :mod:`math` module consists mostly of thin wrappers around the platform C
Mark Dickinson603b7532010-04-06 19:55:03 +0000389 math library functions. Behavior in exceptional cases follows Annex F of
390 the C99 standard where appropriate. The current implementation will raise
391 :exc:`ValueError` for invalid operations like ``sqrt(-1.0)`` or ``log(0.0)``
392 (where C99 Annex F recommends signaling invalid operation or divide-by-zero),
393 and :exc:`OverflowError` for results that overflow (for example,
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000394 ``exp(1000.0)``). A NaN will not be returned from any of the functions
395 above unless one or more of the input arguments was a NaN; in that case,
396 most functions will return a NaN, but (again following C99 Annex F) there
Mark Dickinson603b7532010-04-06 19:55:03 +0000397 are some exceptions to this rule, for example ``pow(float('nan'), 0.0)`` or
398 ``hypot(float('nan'), float('inf'))``.
Georg Brandl116aa622007-08-15 14:28:22 +0000399
Mark Dickinson42dfeec2010-04-06 22:13:37 +0000400 Note that Python makes no effort to distinguish signaling NaNs from
401 quiet NaNs, and behavior for signaling NaNs remains unspecified.
402 Typical behavior is to treat all NaNs as though they were quiet.
Christian Heimes53876d92008-04-19 00:31:39 +0000403
Georg Brandl116aa622007-08-15 14:28:22 +0000404
405.. seealso::
406
407 Module :mod:`cmath`
408 Complex number versions of many of these functions.