blob: b69d6c618dda9342c1d4a1e3cad24e5aa67180e5 [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
34 :class:`Integral` value.
Christian Heimes072c0f12008-01-03 23:01:04 +000035
36
37.. function:: copysign(x, y)
38
Mark Dickinson603b7532010-04-06 19:55:03 +000039 Return *x* with the sign of *y*. On a platform that supports
40 signed zeros, ``copysign(1.0, -0.0)`` returns *-1.0*.
Christian Heimes072c0f12008-01-03 23:01:04 +000041
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
56 :class:`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
136 Return the :class:`Real` value *x* truncated to an :class:`Integral` (usually
Mark Dickinsonbf5c6a92009-01-17 10:21:23 +0000137 an integer). Delegates to ``x.__trunc__()``.
Christian Heimes400adb02008-02-01 08:12:03 +0000138
Christian Heimes400adb02008-02-01 08:12:03 +0000139
Georg Brandl116aa622007-08-15 14:28:22 +0000140Note that :func:`frexp` and :func:`modf` have a different call/return pattern
141than their C equivalents: they take a single argument and return a pair of
142values, rather than returning their second return value through an 'output
143parameter' (there is no such thing in Python).
144
145For the :func:`ceil`, :func:`floor`, and :func:`modf` functions, note that *all*
146floating-point numbers of sufficiently large magnitude are exact integers.
147Python floats typically carry no more than 53 bits of precision (the same as the
148platform C double type), in which case any float *x* with ``abs(x) >= 2**52``
149necessarily has no fractional bits.
150
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000151
152Power and logarithmic functions
153-------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000154
Georg Brandl116aa622007-08-15 14:28:22 +0000155.. function:: exp(x)
156
157 Return ``e**x``.
158
159
Mark Dickinson664b5112009-12-16 20:23:42 +0000160.. function:: expm1(x)
161
Raymond Hettinger1081d482011-03-31 12:04:53 -0700162 Return ``e**x - 1``. For small floats *x*, the subtraction in ``exp(x) - 1``
163 can result in a `significant loss of precision
164 <http://en.wikipedia.org/wiki/Loss_of_significance>`_\; the :func:`expm1`
165 function provides a way to compute this quantity to full precision::
Mark Dickinson664b5112009-12-16 20:23:42 +0000166
167 >>> from math import exp, expm1
168 >>> exp(1e-5) - 1 # gives result accurate to 11 places
169 1.0000050000069649e-05
170 >>> expm1(1e-5) # result accurate to full precision
171 1.0000050000166668e-05
172
Mark Dickinson45f992a2009-12-19 11:20:49 +0000173 .. versionadded:: 3.2
174
Mark Dickinson664b5112009-12-16 20:23:42 +0000175
Georg Brandl116aa622007-08-15 14:28:22 +0000176.. function:: log(x[, base])
177
Georg Brandla6053b42009-09-01 08:11:14 +0000178 With one argument, return the natural logarithm of *x* (to base *e*).
179
180 With two arguments, return the logarithm of *x* to the given *base*,
181 calculated as ``log(x)/log(base)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000182
Georg Brandl116aa622007-08-15 14:28:22 +0000183
Christian Heimes53876d92008-04-19 00:31:39 +0000184.. function:: log1p(x)
185
186 Return the natural logarithm of *1+x* (base *e*). The
187 result is calculated in a way which is accurate for *x* near zero.
188
Christian Heimes53876d92008-04-19 00:31:39 +0000189
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200190.. function:: log2(x)
191
Benjamin Petersoneaee1382011-05-08 19:48:08 -0500192 Return the base-2 logarithm of *x*. This is usually more accurate than
193 ``log(x, 2)``.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200194
195 .. versionadded:: 3.3
196
Victor Stinner9415afc2011-09-21 03:35:18 +0200197 .. seealso::
198
199 :meth:`int.bit_length` returns the number of bits necessary to represent
200 an integer in binary, excluding the sign and leading zeros.
201
Victor Stinnerfa0e3d52011-05-09 01:01:09 +0200202
Georg Brandl116aa622007-08-15 14:28:22 +0000203.. function:: log10(x)
204
Georg Brandla6053b42009-09-01 08:11:14 +0000205 Return the base-10 logarithm of *x*. This is usually more accurate
206 than ``log(x, 10)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000207
208
209.. function:: pow(x, y)
210
Christian Heimesa342c012008-04-20 21:01:16 +0000211 Return ``x`` raised to the power ``y``. Exceptional cases follow
212 Annex 'F' of the C99 standard as far as possible. In particular,
213 ``pow(1.0, x)`` and ``pow(x, 0.0)`` always return ``1.0``, even
214 when ``x`` is a zero or a NaN. If both ``x`` and ``y`` are finite,
215 ``x`` is negative, and ``y`` is not an integer then ``pow(x, y)``
216 is undefined, and raises :exc:`ValueError`.
Christian Heimes53876d92008-04-19 00:31:39 +0000217
Ezio Melotti739d5492013-02-23 04:53:44 +0200218 Unlike the built-in ``**`` operator, :func:`math.pow` converts both
219 its arguments to type :class:`float`. Use ``**`` or the built-in
220 :func:`pow` function for computing exact integer powers.
221
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223.. function:: sqrt(x)
224
225 Return the square root of *x*.
226
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000227Trigonometric functions
228-----------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230
231.. function:: acos(x)
232
233 Return the arc cosine of *x*, in radians.
234
235
236.. function:: asin(x)
237
238 Return the arc sine of *x*, in radians.
239
240
241.. function:: atan(x)
242
243 Return the arc tangent of *x*, in radians.
244
245
246.. function:: atan2(y, x)
247
248 Return ``atan(y / x)``, in radians. The result is between ``-pi`` and ``pi``.
249 The vector in the plane from the origin to point ``(x, y)`` makes this angle
250 with the positive X axis. The point of :func:`atan2` is that the signs of both
251 inputs are known to it, so it can compute the correct quadrant for the angle.
Mark Dickinson603b7532010-04-06 19:55:03 +0000252 For example, ``atan(1)`` and ``atan2(1, 1)`` are both ``pi/4``, but ``atan2(-1,
Georg Brandl116aa622007-08-15 14:28:22 +0000253 -1)`` is ``-3*pi/4``.
254
255
256.. function:: cos(x)
257
258 Return the cosine of *x* radians.
259
260
261.. function:: hypot(x, y)
262
263 Return the Euclidean norm, ``sqrt(x*x + y*y)``. This is the length of the vector
264 from the origin to point ``(x, y)``.
265
266
267.. function:: sin(x)
268
269 Return the sine of *x* radians.
270
271
272.. function:: tan(x)
273
274 Return the tangent of *x* radians.
275
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000276Angular conversion
277------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000278
279
280.. function:: degrees(x)
281
282 Converts angle *x* from radians to degrees.
283
284
285.. function:: radians(x)
286
287 Converts angle *x* from degrees to radians.
288
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000289Hyperbolic functions
290--------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000291
Raymond Hettinger1081d482011-03-31 12:04:53 -0700292`Hyperbolic functions <http://en.wikipedia.org/wiki/Hyperbolic_function>`_
293are analogs of trigonometric functions that are based on hyperbolas
294instead of circles.
Georg Brandl116aa622007-08-15 14:28:22 +0000295
Christian Heimesa342c012008-04-20 21:01:16 +0000296.. function:: acosh(x)
297
298 Return the inverse hyperbolic cosine of *x*.
299
Christian Heimesa342c012008-04-20 21:01:16 +0000300
301.. function:: asinh(x)
302
303 Return the inverse hyperbolic sine of *x*.
304
Christian Heimesa342c012008-04-20 21:01:16 +0000305
306.. function:: atanh(x)
307
308 Return the inverse hyperbolic tangent of *x*.
309
Christian Heimesa342c012008-04-20 21:01:16 +0000310
Georg Brandl116aa622007-08-15 14:28:22 +0000311.. function:: cosh(x)
312
313 Return the hyperbolic cosine of *x*.
314
315
316.. function:: sinh(x)
317
318 Return the hyperbolic sine of *x*.
319
320
321.. function:: tanh(x)
322
323 Return the hyperbolic tangent of *x*.
324
Christian Heimes53876d92008-04-19 00:31:39 +0000325
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000326Special functions
327-----------------
328
Mark Dickinson45f992a2009-12-19 11:20:49 +0000329.. function:: erf(x)
330
Raymond Hettinger1081d482011-03-31 12:04:53 -0700331 Return the `error function <http://en.wikipedia.org/wiki/Error_function>`_ at
332 *x*.
333
334 The :func:`erf` function can be used to compute traditional statistical
335 functions such as the `cumulative standard normal distribution
336 <http://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function>`_::
337
338 def phi(x):
339 'Cumulative distribution function for the standard normal distribution'
340 return (1.0 + erf(x / sqrt(2.0))) / 2.0
Mark Dickinson45f992a2009-12-19 11:20:49 +0000341
342 .. versionadded:: 3.2
343
344
345.. function:: erfc(x)
346
Raymond Hettinger1081d482011-03-31 12:04:53 -0700347 Return the complementary error function at *x*. The `complementary error
348 function <http://en.wikipedia.org/wiki/Error_function>`_ is defined as
Raymond Hettinger12e6c252011-03-31 13:59:24 -0700349 ``1.0 - erf(x)``. It is used for large values of *x* where a subtraction
350 from one would cause a `loss of significance
Raymond Hettinger1081d482011-03-31 12:04:53 -0700351 <http://en.wikipedia.org/wiki/Loss_of_significance>`_\.
Mark Dickinson45f992a2009-12-19 11:20:49 +0000352
353 .. versionadded:: 3.2
354
355
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000356.. function:: gamma(x)
357
Raymond Hettinger12e6c252011-03-31 13:59:24 -0700358 Return the `Gamma function <http://en.wikipedia.org/wiki/Gamma_function>`_ at
359 *x*.
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000360
Mark Dickinson56e09662009-10-01 16:13:29 +0000361 .. versionadded:: 3.2
Mark Dickinson12c4bdb2009-09-28 19:21:11 +0000362
363
Mark Dickinson05d2e082009-12-11 20:17:17 +0000364.. function:: lgamma(x)
365
366 Return the natural logarithm of the absolute value of the Gamma
367 function at *x*.
368
Mark Dickinson45f992a2009-12-19 11:20:49 +0000369 .. versionadded:: 3.2
Mark Dickinson05d2e082009-12-11 20:17:17 +0000370
371
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000372Constants
Mark Dickinson60fe6b02009-06-02 12:53:15 +0000373---------
Georg Brandl116aa622007-08-15 14:28:22 +0000374
375.. data:: pi
376
Mark Dickinson603b7532010-04-06 19:55:03 +0000377 The mathematical constant π = 3.141592..., to available precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379
380.. data:: e
381
Mark Dickinson603b7532010-04-06 19:55:03 +0000382 The mathematical constant e = 2.718281..., to available precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000383
Christian Heimes53876d92008-04-19 00:31:39 +0000384
Georg Brandl495f7b52009-10-27 15:28:25 +0000385.. impl-detail::
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387 The :mod:`math` module consists mostly of thin wrappers around the platform C
Mark Dickinson603b7532010-04-06 19:55:03 +0000388 math library functions. Behavior in exceptional cases follows Annex F of
389 the C99 standard where appropriate. The current implementation will raise
390 :exc:`ValueError` for invalid operations like ``sqrt(-1.0)`` or ``log(0.0)``
391 (where C99 Annex F recommends signaling invalid operation or divide-by-zero),
392 and :exc:`OverflowError` for results that overflow (for example,
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000393 ``exp(1000.0)``). A NaN will not be returned from any of the functions
394 above unless one or more of the input arguments was a NaN; in that case,
395 most functions will return a NaN, but (again following C99 Annex F) there
Mark Dickinson603b7532010-04-06 19:55:03 +0000396 are some exceptions to this rule, for example ``pow(float('nan'), 0.0)`` or
397 ``hypot(float('nan'), float('inf'))``.
Georg Brandl116aa622007-08-15 14:28:22 +0000398
Mark Dickinson42dfeec2010-04-06 22:13:37 +0000399 Note that Python makes no effort to distinguish signaling NaNs from
400 quiet NaNs, and behavior for signaling NaNs remains unspecified.
401 Typical behavior is to treat all NaNs as though they were quiet.
Christian Heimes53876d92008-04-19 00:31:39 +0000402
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404.. seealso::
405
406 Module :mod:`cmath`
407 Complex number versions of many of these functions.