From 844dc5e44c35eed6ec753f729b18d7ad6e03d761 Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Sat, 2 Nov 2024 16:37:56 +0100 Subject: [PATCH 01/14] Move trigonometric and hyperbolic functions together --- Doc/library/math.rst | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index 5ce2ad2d6aec47..49960139cd5722 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -69,6 +69,11 @@ noted otherwise, all return values are floats. :func:`pow(x, y) ` *x* raised to the power *y* :func:`sqrt(x) ` Square root of *x* +**Angular conversion** +-------------------------------------------------------------------------------------------------- +:func:`degrees(x) ` Convert angle *x* from radians to degrees +:func:`radians(x) ` Convert angle *x* from degrees to radians + **Trigonometric functions** -------------------------------------------------------------------------------------------------- :func:`acos(x) ` Arc cosine of *x* @@ -81,11 +86,6 @@ noted otherwise, all return values are floats. :func:`sin(x) ` Sine of *x* :func:`tan(x) ` Tangent of *x* -**Angular conversion** --------------------------------------------------------------------------------------------------- -:func:`degrees(x) ` Convert angle *x* from radians to degrees -:func:`radians(x) ` Convert angle *x* from degrees to radians - **Hyperbolic functions** -------------------------------------------------------------------------------------------------- :func:`acosh(x) ` Inverse hyperbolic cosine of *x* @@ -557,6 +557,19 @@ Power and logarithmic functions Return the square root of *x*. +Angular conversion +------------------ + +.. function:: degrees(x) + + Convert angle *x* from radians to degrees. + + +.. function:: radians(x) + + Convert angle *x* from degrees to radians. + + Trigonometric functions ----------------------- @@ -636,19 +649,6 @@ Trigonometric functions Return the tangent of *x* radians. -Angular conversion ------------------- - -.. function:: degrees(x) - - Convert angle *x* from radians to degrees. - - -.. function:: radians(x) - - Convert angle *x* from degrees to radians. - - Hyperbolic functions -------------------- From d97a345cdb29d7273b66ff344c0ff8784cfd8f54 Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Sat, 2 Nov 2024 16:38:38 +0100 Subject: [PATCH 02/14] Power, exponential and logarithmic functions --- Doc/library/math.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index 49960139cd5722..6665d61fc2b9c8 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -56,7 +56,7 @@ noted otherwise, all return values are floats. :func:`trunc(x) ` Integer part of *x* :func:`ulp(x) ` Value of the least significant bit of *x* -**Power and logarithmic functions** +**Power, exponential and logarithmic functions** -------------------------------------------------------------------------------------------------- :func:`cbrt(x) ` Cube root of *x* :func:`exp(x) ` *e* raised to the power *x* @@ -459,8 +459,8 @@ platform C double type), in which case any float *x* with ``abs(x) >= 2**52`` necessarily has no fractional bits. -Power and logarithmic functions -------------------------------- +Power, exponential and logarithmic functions +-------------------------------------------- .. function:: cbrt(x) From 0862e283cd5b203f6a94a7cbd2368c95fde5b77f Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Sat, 2 Nov 2024 16:55:56 +0100 Subject: [PATCH 03/14] Error and gamma functions --- Doc/library/math.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index 6665d61fc2b9c8..e7f9486a454886 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -95,7 +95,7 @@ noted otherwise, all return values are floats. :func:`sinh(x) ` Hyperbolic sine of *x* :func:`tanh(x) ` Hyperbolic tangent of *x* -**Special functions** +**Error and gamma functions** -------------------------------------------------------------------------------------------------- :func:`erf(x) ` `Error function `_ at *x* :func:`erfc(x) ` `Complementary error function `_ at *x* @@ -686,8 +686,8 @@ instead of circles. Return the hyperbolic tangent of *x*. -Special functions ------------------ +Error and gamma functions +------------------------- .. function:: erf(x) From f8378e27d98333f30c8244d7456130e114293778 Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Sat, 2 Nov 2024 16:56:10 +0100 Subject: [PATCH 04/14] fmod short description --- Doc/library/math.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index e7f9486a454886..61f6f4d128ab48 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -186,7 +186,10 @@ Number-theoretic and representation functions .. function:: fmod(x, y) - Return ``fmod(x, y)``, as defined by the platform C library. Note that the + Return the remainder of division ``x / y``, + as defined by the platform C library function ``fmod(x, y)``. + + Note that the Python expression ``x % y`` may not return the same result. The intent of the C standard is that ``fmod(x, y)`` be exactly (mathematically; to infinite precision) equal to ``x - n*y`` for some integer *n* such that the result has From 462dc0289c841bf134999dc7d861490ca6b05924 Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Sat, 2 Nov 2024 19:17:06 +0100 Subject: [PATCH 05/14] Reorder documentation --- Doc/library/math.rst | 436 ++++++++++++++++++++----------------------- 1 file changed, 207 insertions(+), 229 deletions(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index 61f6f4d128ab48..dd5db80fbb2f75 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -27,33 +27,36 @@ noted otherwise, all return values are floats. ==================================================== ============================================ -**Number-theoretic and representation functions** +**Number-theoretic functions** -------------------------------------------------------------------------------------------------- -:func:`ceil(x) ` Ceiling of *x*, the smallest integer greater than or equal to *x* :func:`comb(n, k) ` Number of ways to choose *k* items from *n* items without repetition and without order -:func:`copysign(x, y) ` Magnitude (absolute value) of *x* with the sign of *y* -:func:`fabs(x) ` Absolute value of *x* :func:`factorial(n) ` *n* factorial +:func:`gcd(*integers) ` Greatest common divisor of the integer arguments +:func:`isqrt(n) ` Integer square root of a nonnegative integer *n* +:func:`lcm(*integers) ` Least common multiple of the integer arguments +:func:`perm(n, k) ` Number of ways to choose *k* items from *n* items without repetition and with order + +**Basic floating point operations** +-------------------------------------------------------------------------------------------------- +:func:`ceil(x) ` Ceiling of *x*, the smallest integer greater than or equal to *x* +:func:`fabs(x) ` Absolute value of *x* :func:`floor (x) ` Floor of *x*, the largest integer less than or equal to *x* :func:`fma(x, y, z) ` Fused multiply-add operation: ``(x * y) + z`` :func:`fmod(x, y) ` Remainder of division ``x / y`` +:func:`modf(x) ` Fractional and integer parts of *x* +:func:`remainder(x, y) ` Remainder of *x* with respect to *y* +:func:`trunc(x) ` Integer part of *x* + +**Floating point manipulation functions** +-------------------------------------------------------------------------------------------------- +:func:`copysign(x, y) ` Magnitude (absolute value) of *x* with the sign of *y* :func:`frexp(x) ` Mantissa and exponent of *x* -:func:`fsum(iterable) ` Sum of values in the input *iterable* -:func:`gcd(*integers) ` Greatest common divisor of the integer arguments :func:`isclose(a, b, rel_tol, abs_tol) ` Check if the values *a* and *b* are close to each other :func:`isfinite(x) ` Check if *x* is neither an infinity nor a NaN :func:`isinf(x) ` Check if *x* is a positive or negative infinity :func:`isnan(x) ` Check if *x* is a NaN (not a number) -:func:`isqrt(n) ` Integer square root of a nonnegative integer *n* -:func:`lcm(*integers) ` Least common multiple of the integer arguments :func:`ldexp(x, i) ` ``x * (2**i)``, inverse of function :func:`frexp` -:func:`modf(x) ` Fractional and integer parts of *x* :func:`nextafter(x, y, steps) ` Floating-point value *steps* steps after *x* towards *y* -:func:`perm(n, k) ` Number of ways to choose *k* items from *n* items without repetition and with order -:func:`prod(iterable, start) ` Product of elements in the input *iterable* with a *start* value -:func:`remainder(x, y) ` Remainder of *x* with respect to *y* -:func:`sumprod(p, q) ` Sum of products from two iterables *p* and *q* -:func:`trunc(x) ` Integer part of *x* :func:`ulp(x) ` Value of the least significant bit of *x* **Power, exponential and logarithmic functions** @@ -69,6 +72,14 @@ noted otherwise, all return values are floats. :func:`pow(x, y) ` *x* raised to the power *y* :func:`sqrt(x) ` Square root of *x* +**Summation and product functions** +-------------------------------------------------------------------------------------------------- +:func:`dist(p, q) ` Euclidean distance between two points *p* and *q* given as an iterable of coordinates +:func:`fsum(iterable) ` Sum of values in the input *iterable* +:func:`hypot(*coordinates) ` Euclidean norm of an iterable of coordinates +:func:`prod(iterable, start) ` Product of elements in the input *iterable* with a *start* value +:func:`sumprod(p, q) ` Sum of products from two iterables *p* and *q* + **Angular conversion** -------------------------------------------------------------------------------------------------- :func:`degrees(x) ` Convert angle *x* from radians to degrees @@ -81,8 +92,6 @@ noted otherwise, all return values are floats. :func:`atan(x) ` Arc tangent of *x* :func:`atan2(y, x) ` ``atan(y / x)`` :func:`cos(x) ` Cosine of *x* -:func:`dist(p, q) ` Euclidean distance between two points *p* and *q* given as an iterable of coordinates -:func:`hypot(*coordinates) ` Euclidean norm of an iterable of coordinates :func:`sin(x) ` Sine of *x* :func:`tan(x) ` Tangent of *x* @@ -112,16 +121,34 @@ noted otherwise, all return values are floats. ==================================================== ============================================ -Number-theoretic and representation functions ---------------------------------------------- +.. impl-detail:: -.. function:: ceil(x) + The :mod:`math` module consists mostly of thin wrappers around the platform C + math library functions. Behavior in exceptional cases follows Annex F of + the C99 standard where appropriate. The current implementation will raise + :exc:`ValueError` for invalid operations like ``sqrt(-1.0)`` or ``log(0.0)`` + (where C99 Annex F recommends signaling invalid operation or divide-by-zero), + and :exc:`OverflowError` for results that overflow (for example, + ``exp(1000.0)``). A NaN will not be returned from any of the functions + above unless one or more of the input arguments was a NaN; in that case, + most functions will return a NaN, but (again following C99 Annex F) there + are some exceptions to this rule, for example ``pow(float('nan'), 0.0)`` or + ``hypot(float('nan'), float('inf'))``. - Return the ceiling of *x*, the smallest integer greater than or equal to *x*. - If *x* is not a float, delegates to :meth:`x.__ceil__ `, - which should return an :class:`~numbers.Integral` value. + Note that Python makes no effort to distinguish signaling NaNs from + quiet NaNs, and behavior for signaling NaNs remains unspecified. + Typical behavior is to treat all NaNs as though they were quiet. + + +.. seealso:: + + Module :mod:`cmath` + Complex number versions of many of these functions. +Number-theoretic functions +-------------------------- + .. function:: comb(n, k) Return the number of ways to choose *k* items from *n* items without repetition @@ -140,25 +167,36 @@ Number-theoretic and representation functions .. versionadded:: 3.8 -.. function:: copysign(x, y) +.. function:: factorial(n) - Return a float with the magnitude (absolute value) of *x* but the sign of - *y*. On platforms that support signed zeros, ``copysign(1.0, -0.0)`` - returns *-1.0*. + Return the number of ways to choose *k* items from *n* items + without repetition and with order. + Evaluates to ``n! / (n - k)!`` when ``k <= n`` and evaluates + to zero when ``k > n``. -.. function:: fabs(x) + If *k* is not specified or is ``None``, then *k* defaults to *n* + and the function returns ``n!``. - Return the absolute value of *x*. + Raises :exc:`TypeError` if either of the arguments are not integers. + Raises :exc:`ValueError` if either of the arguments are negative. + .. versionadded:: 3.8 -.. function:: factorial(n) - Return *n* factorial as an integer. Raises :exc:`ValueError` if *n* is not integral or - is negative. +Basic floating point operations +------------------------------- - .. versionchanged:: 3.10 - Floats with integral values (like ``5.0``) are no longer accepted. +.. function:: ceil(x) + + Return the ceiling of *x*, the smallest integer greater than or equal to *x*. + If *x* is not a float, delegates to :meth:`x.__ceil__ `, + which should return an :class:`~numbers.Integral` value. + + +.. function:: fabs(x) + + Return the absolute value of *x*. .. function:: floor(x) @@ -202,43 +240,70 @@ Number-theoretic and representation functions floats, while Python's ``x % y`` is preferred when working with integers. -.. function:: frexp(x) +.. function:: modf(x) - Return the mantissa and exponent of *x* as the pair ``(m, e)``. *m* is a float - and *e* is an integer such that ``x == m * 2**e`` exactly. If *x* is zero, - returns ``(0.0, 0)``, otherwise ``0.5 <= abs(m) < 1``. This is used to "pick - apart" the internal representation of a float in a portable way. + Return the fractional and integer parts of *x*. Both results carry the sign + of *x* and are floats. -.. function:: fsum(iterable) +.. function:: remainder(x, y) - Return an accurate floating-point sum of values in the iterable. Avoids - loss of precision by tracking multiple intermediate partial sums. + Return the IEEE 754-style remainder of *x* with respect to *y*. For + finite *x* and finite nonzero *y*, this is the difference ``x - n*y``, + where ``n`` is the closest integer to the exact value of the quotient ``x / + y``. If ``x / y`` is exactly halfway between two consecutive integers, the + nearest *even* integer is used for ``n``. The remainder ``r = remainder(x, + y)`` thus always satisfies ``abs(r) <= 0.5 * abs(y)``. - The algorithm's accuracy depends on IEEE-754 arithmetic guarantees and the - typical case where the rounding mode is half-even. On some non-Windows - builds, the underlying C library uses extended precision addition and may - occasionally double-round an intermediate sum causing it to be off in its - least significant bit. + Special cases follow IEEE 754: in particular, ``remainder(x, math.inf)`` is + *x* for any finite *x*, and ``remainder(x, 0)`` and + ``remainder(math.inf, x)`` raise :exc:`ValueError` for any non-NaN *x*. + If the result of the remainder operation is zero, that zero will have + the same sign as *x*. - For further discussion and two alternative approaches, see the `ASPN cookbook - recipes for accurate floating-point summation - `_\. + On platforms using IEEE 754 binary floating point, the result of this + operation is always exactly representable: no rounding error is introduced. + .. versionadded:: 3.7 -.. function:: gcd(*integers) - Return the greatest common divisor of the specified integer arguments. - If any of the arguments is nonzero, then the returned value is the largest - positive integer that is a divisor of all arguments. If all arguments - are zero, then the returned value is ``0``. ``gcd()`` without arguments - returns ``0``. +.. function:: trunc(x) - .. versionadded:: 3.5 + Return *x* with the fractional part + removed, leaving the integer part. This rounds toward 0: ``trunc()`` is + equivalent to :func:`floor` for positive *x*, and equivalent to :func:`ceil` + for negative *x*. If *x* is not a float, delegates to :meth:`x.__trunc__ + `, which should return an :class:`~numbers.Integral` value. + + +For the :func:`ceil`, :func:`floor`, and :func:`modf` functions, note that *all* +floating-point numbers of sufficiently large magnitude are exact integers. +Python floats typically carry no more than 53 bits of precision (the same as the +platform C double type), in which case any float *x* with ``abs(x) >= 2**52`` +necessarily has no fractional bits. + +Note that :func:`modf` has a different call/return pattern +than its C equivalents: it takes a single argument and return a pair of +values, rather than returning its second return value through an 'output +parameter' (there is no such thing in Python). + + +Floating point manipulation functions +------------------------------------- + +.. function:: copysign(x, y) + + Return a float with the magnitude (absolute value) of *x* but the sign of + *y*. On platforms that support signed zeros, ``copysign(1.0, -0.0)`` + returns *-1.0*. + + +.. function:: frexp(x) - .. versionchanged:: 3.9 - Added support for an arbitrary number of arguments. Formerly, only two - arguments were supported. + Return the mantissa and exponent of *x* as the pair ``(m, e)``. *m* is a float + and *e* is an integer such that ``x == m * 2**e`` exactly. If *x* is zero, + returns ``(0.0, 0)``, otherwise ``0.5 <= abs(m) < 1``. This is used to "pick + apart" the internal representation of a float in a portable way. .. function:: isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) @@ -294,43 +359,12 @@ Number-theoretic and representation functions Return ``True`` if *x* is a NaN (not a number), and ``False`` otherwise. -.. function:: isqrt(n) - - Return the integer square root of the nonnegative integer *n*. This is the - floor of the exact square root of *n*, or equivalently the greatest integer - *a* such that *a*\ ² |nbsp| ≤ |nbsp| *n*. - - For some applications, it may be more convenient to have the least integer - *a* such that *n* |nbsp| ≤ |nbsp| *a*\ ², or in other words the ceiling of - the exact square root of *n*. For positive *n*, this can be computed using - ``a = 1 + isqrt(n - 1)``. - - .. versionadded:: 3.8 - - -.. function:: lcm(*integers) - - Return the least common multiple of the specified integer arguments. - If all arguments are nonzero, then the returned value is the smallest - positive integer that is a multiple of all arguments. If any of the arguments - is zero, then the returned value is ``0``. ``lcm()`` without arguments - returns ``1``. - - .. versionadded:: 3.9 - - .. function:: ldexp(x, i) Return ``x * (2**i)``. This is essentially the inverse of function :func:`frexp`. -.. function:: modf(x) - - Return the fractional and integer parts of *x*. Both results carry the sign - of *x* and are floats. - - .. function:: nextafter(x, y, steps=1) Return the floating-point value *steps* steps after *x* towards *y*. @@ -351,79 +385,6 @@ Number-theoretic and representation functions .. versionchanged:: 3.12 Added the *steps* argument. -.. function:: perm(n, k=None) - - Return the number of ways to choose *k* items from *n* items - without repetition and with order. - - Evaluates to ``n! / (n - k)!`` when ``k <= n`` and evaluates - to zero when ``k > n``. - - If *k* is not specified or is ``None``, then *k* defaults to *n* - and the function returns ``n!``. - - Raises :exc:`TypeError` if either of the arguments are not integers. - Raises :exc:`ValueError` if either of the arguments are negative. - - .. versionadded:: 3.8 - - -.. function:: prod(iterable, *, start=1) - - Calculate the product of all the elements in the input *iterable*. - The default *start* value for the product is ``1``. - - When the iterable is empty, return the start value. This function is - intended specifically for use with numeric values and may reject - non-numeric types. - - .. versionadded:: 3.8 - - -.. function:: remainder(x, y) - - Return the IEEE 754-style remainder of *x* with respect to *y*. For - finite *x* and finite nonzero *y*, this is the difference ``x - n*y``, - where ``n`` is the closest integer to the exact value of the quotient ``x / - y``. If ``x / y`` is exactly halfway between two consecutive integers, the - nearest *even* integer is used for ``n``. The remainder ``r = remainder(x, - y)`` thus always satisfies ``abs(r) <= 0.5 * abs(y)``. - - Special cases follow IEEE 754: in particular, ``remainder(x, math.inf)`` is - *x* for any finite *x*, and ``remainder(x, 0)`` and - ``remainder(math.inf, x)`` raise :exc:`ValueError` for any non-NaN *x*. - If the result of the remainder operation is zero, that zero will have - the same sign as *x*. - - On platforms using IEEE 754 binary floating point, the result of this - operation is always exactly representable: no rounding error is introduced. - - .. versionadded:: 3.7 - - -.. function:: sumprod(p, q) - - Return the sum of products of values from two iterables *p* and *q*. - - Raises :exc:`ValueError` if the inputs do not have the same length. - - Roughly equivalent to:: - - sum(map(operator.mul, p, q, strict=True)) - - For float and mixed int/float inputs, the intermediate products - and sums are computed with extended precision. - - .. versionadded:: 3.12 - - -.. function:: trunc(x) - - Return *x* with the fractional part - removed, leaving the integer part. This rounds toward 0: ``trunc()`` is - equivalent to :func:`floor` for positive *x*, and equivalent to :func:`ceil` - for negative *x*. If *x* is not a float, delegates to :meth:`x.__trunc__ - `, which should return an :class:`~numbers.Integral` value. .. function:: ulp(x) @@ -450,17 +411,11 @@ Number-theoretic and representation functions .. versionadded:: 3.9 -Note that :func:`frexp` and :func:`modf` have a different call/return pattern -than their C equivalents: they take a single argument and return a pair of -values, rather than returning their second return value through an 'output +Note that :func:`frexp` has a different call/return pattern +than its C equivalents: it takes a single argument and return a pair of +values, rather than returning its second return value through an 'output parameter' (there is no such thing in Python). -For the :func:`ceil`, :func:`floor`, and :func:`modf` functions, note that *all* -floating-point numbers of sufficiently large magnitude are exact integers. -Python floats typically carry no more than 53 bits of precision (the same as the -platform C double type), in which case any float *x* with ``abs(x) >= 2**52`` -necessarily has no fractional bits. - Power, exponential and logarithmic functions -------------------------------------------- @@ -560,6 +515,86 @@ Power, exponential and logarithmic functions Return the square root of *x*. +Summation and product functions +------------------------------- + +.. function:: dist(p, q) + + Return the Euclidean distance between two points *p* and *q*, each + given as a sequence (or iterable) of coordinates. The two points + must have the same dimension. + + Roughly equivalent to:: + + sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) + + .. versionadded:: 3.8 + + +.. function:: fsum(iterable) + + Return an accurate floating-point sum of values in the iterable. Avoids + loss of precision by tracking multiple intermediate partial sums. + + The algorithm's accuracy depends on IEEE-754 arithmetic guarantees and the + typical case where the rounding mode is half-even. On some non-Windows + builds, the underlying C library uses extended precision addition and may + occasionally double-round an intermediate sum causing it to be off in its + least significant bit. + + For further discussion and two alternative approaches, see the `ASPN cookbook + recipes for accurate floating-point summation + `_\. + + +.. function:: hypot(*coordinates) + + Return the Euclidean norm, ``sqrt(sum(x**2 for x in coordinates))``. + This is the length of the vector from the origin to the point + given by the coordinates. + + For a two dimensional point ``(x, y)``, this is equivalent to computing + the hypotenuse of a right triangle using the Pythagorean theorem, + ``sqrt(x*x + y*y)``. + + .. versionchanged:: 3.8 + Added support for n-dimensional points. Formerly, only the two + dimensional case was supported. + + .. versionchanged:: 3.10 + Improved the algorithm's accuracy so that the maximum error is + under 1 ulp (unit in the last place). More typically, the result + is almost always correctly rounded to within 1/2 ulp. + + +.. function:: prod(iterable, *, start=1) + + Calculate the product of all the elements in the input *iterable*. + The default *start* value for the product is ``1``. + + When the iterable is empty, return the start value. This function is + intended specifically for use with numeric values and may reject + non-numeric types. + + .. versionadded:: 3.8 + + +.. function:: sumprod(p, q) + + Return the sum of products of values from two iterables *p* and *q*. + + Raises :exc:`ValueError` if the inputs do not have the same length. + + Roughly equivalent to:: + + sum(map(operator.mul, p, q, strict=True)) + + For float and mixed int/float inputs, the intermediate products + and sums are computed with extended precision. + + .. versionadded:: 3.12 + + Angular conversion ------------------ @@ -609,39 +644,6 @@ Trigonometric functions Return the cosine of *x* radians. -.. function:: dist(p, q) - - Return the Euclidean distance between two points *p* and *q*, each - given as a sequence (or iterable) of coordinates. The two points - must have the same dimension. - - Roughly equivalent to:: - - sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) - - .. versionadded:: 3.8 - - -.. function:: hypot(*coordinates) - - Return the Euclidean norm, ``sqrt(sum(x**2 for x in coordinates))``. - This is the length of the vector from the origin to the point - given by the coordinates. - - For a two dimensional point ``(x, y)``, this is equivalent to computing - the hypotenuse of a right triangle using the Pythagorean theorem, - ``sqrt(x*x + y*y)``. - - .. versionchanged:: 3.8 - Added support for n-dimensional points. Formerly, only the two - dimensional case was supported. - - .. versionchanged:: 3.10 - Improved the algorithm's accuracy so that the maximum error is - under 1 ulp (unit in the last place). More typically, the result - is almost always correctly rounded to within 1/2 ulp. - - .. function:: sin(x) Return the sine of *x* radians. @@ -793,29 +795,5 @@ Constants It is now always available. -.. impl-detail:: - - The :mod:`math` module consists mostly of thin wrappers around the platform C - math library functions. Behavior in exceptional cases follows Annex F of - the C99 standard where appropriate. The current implementation will raise - :exc:`ValueError` for invalid operations like ``sqrt(-1.0)`` or ``log(0.0)`` - (where C99 Annex F recommends signaling invalid operation or divide-by-zero), - and :exc:`OverflowError` for results that overflow (for example, - ``exp(1000.0)``). A NaN will not be returned from any of the functions - above unless one or more of the input arguments was a NaN; in that case, - most functions will return a NaN, but (again following C99 Annex F) there - are some exceptions to this rule, for example ``pow(float('nan'), 0.0)`` or - ``hypot(float('nan'), float('inf'))``. - - Note that Python makes no effort to distinguish signaling NaNs from - quiet NaNs, and behavior for signaling NaNs remains unspecified. - Typical behavior is to treat all NaNs as though they were quiet. - - -.. seealso:: - - Module :mod:`cmath` - Complex number versions of many of these functions. - .. |nbsp| unicode:: 0xA0 :trim: From 01ec56ec610dc176be8d91c5f76e36b35cca134e Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Sun, 3 Nov 2024 00:51:27 +0100 Subject: [PATCH 06/14] Keep "Special functions" --- Doc/library/math.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index dd5db80fbb2f75..acf44830afc1a2 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -104,7 +104,7 @@ noted otherwise, all return values are floats. :func:`sinh(x) ` Hyperbolic sine of *x* :func:`tanh(x) ` Hyperbolic tangent of *x* -**Error and gamma functions** +**Special functions** -------------------------------------------------------------------------------------------------- :func:`erf(x) ` `Error function `_ at *x* :func:`erfc(x) ` `Complementary error function `_ at *x* @@ -691,7 +691,7 @@ instead of circles. Return the hyperbolic tangent of *x*. -Error and gamma functions +Special functions ------------------------- .. function:: erf(x) From 71afe0a873891a48dd62433b3b7f23a0adbdf6e9 Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Sun, 3 Nov 2024 00:49:41 +0100 Subject: [PATCH 07/14] Floating point arithmetic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com> --- Doc/library/math.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index acf44830afc1a2..a21149d71a44d6 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -36,7 +36,7 @@ noted otherwise, all return values are floats. :func:`lcm(*integers) ` Least common multiple of the integer arguments :func:`perm(n, k) ` Number of ways to choose *k* items from *n* items without repetition and with order -**Basic floating point operations** +**Floating point arithmetic** -------------------------------------------------------------------------------------------------- :func:`ceil(x) ` Ceiling of *x*, the smallest integer greater than or equal to *x* :func:`fabs(x) ` Absolute value of *x* From ab69732e06c5f252735c726f0b50c70bf452eff6 Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Sun, 3 Nov 2024 12:35:36 +0100 Subject: [PATCH 08/14] Fix whitespace Co-authored-by: Sergey B Kirpichev --- Doc/library/math.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index a21149d71a44d6..f9310a96455b25 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -40,7 +40,7 @@ noted otherwise, all return values are floats. -------------------------------------------------------------------------------------------------- :func:`ceil(x) ` Ceiling of *x*, the smallest integer greater than or equal to *x* :func:`fabs(x) ` Absolute value of *x* -:func:`floor (x) ` Floor of *x*, the largest integer less than or equal to *x* +:func:`floor(x) ` Floor of *x*, the largest integer less than or equal to *x* :func:`fma(x, y, z) ` Fused multiply-add operation: ``(x * y) + z`` :func:`fmod(x, y) ` Remainder of division ``x / y`` :func:`modf(x) ` Fractional and integer parts of *x* From 28e687c5ab01d12085106e9141acf8766893c035 Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Sun, 3 Nov 2024 12:39:51 +0100 Subject: [PATCH 09/14] Sync table names and section headers --- Doc/library/math.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index f9310a96455b25..7b8fbcf3cac1ea 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -184,8 +184,8 @@ Number-theoretic functions .. versionadded:: 3.8 -Basic floating point operations -------------------------------- +Floating point arithmetic +------------------------- .. function:: ceil(x) From a983ae149bf926756b41286ecdd56b2b886cd80f Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Sun, 3 Nov 2024 12:44:28 +0100 Subject: [PATCH 10/14] Fix title formatting --- Doc/library/math.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index 7b8fbcf3cac1ea..77436baecf6671 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -692,7 +692,7 @@ instead of circles. Special functions -------------------------- +----------------- .. function:: erf(x) From f831a1d9771c4a509c010537a34e21c65c3a4a7b Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Wed, 6 Nov 2024 03:54:38 +0100 Subject: [PATCH 11/14] Fix after merge --- Doc/library/math.rst | 49 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index 77436baecf6671..10430e2c79d857 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -169,6 +169,55 @@ Number-theoretic functions .. function:: factorial(n) + Return *n* factorial as an integer. Raises :exc:`ValueError` if *n* is not integral or + is negative. + + .. versionchanged:: 3.10 + Floats with integral values (like ``5.0``) are no longer accepted. + + +.. function:: gcd(*integers) + + Return the greatest common divisor of the specified integer arguments. + If any of the arguments is nonzero, then the returned value is the largest + positive integer that is a divisor of all arguments. If all arguments + are zero, then the returned value is ``0``. ``gcd()`` without arguments + returns ``0``. + + .. versionadded:: 3.5 + + .. versionchanged:: 3.9 + Added support for an arbitrary number of arguments. Formerly, only two + arguments were supported. + + +.. function:: isqrt(n) + + Return the integer square root of the nonnegative integer *n*. This is the + floor of the exact square root of *n*, or equivalently the greatest integer + *a* such that *a*\ ² |nbsp| ≤ |nbsp| *n*. + + For some applications, it may be more convenient to have the least integer + *a* such that *n* |nbsp| ≤ |nbsp| *a*\ ², or in other words the ceiling of + the exact square root of *n*. For positive *n*, this can be computed using + ``a = 1 + isqrt(n - 1)``. + + .. versionadded:: 3.8 + + +.. function:: lcm(*integers) + + Return the least common multiple of the specified integer arguments. + If all arguments are nonzero, then the returned value is the smallest + positive integer that is a multiple of all arguments. If any of the arguments + is zero, then the returned value is ``0``. ``lcm()`` without arguments + returns ``1``. + + .. versionadded:: 3.9 + + +.. function:: perm(n, k=None) + Return the number of ways to choose *k* items from *n* items without repetition and with order. From 40fd57964c125e28d2c8a8c56141106e6f65dea8 Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Tue, 12 Nov 2024 18:22:50 +0100 Subject: [PATCH 12/14] Revert description modification for fmod Co-authored-by: Sergey B Kirpichev --- Doc/library/math.rst | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index 10430e2c79d857..bbbee40f3e32b7 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -273,10 +273,7 @@ Floating point arithmetic .. function:: fmod(x, y) - Return the remainder of division ``x / y``, - as defined by the platform C library function ``fmod(x, y)``. - - Note that the + Return ``fmod(x, y)``, as defined by the platform C library. Note that the Python expression ``x % y`` may not return the same result. The intent of the C standard is that ``fmod(x, y)`` be exactly (mathematically; to infinite precision) equal to ``x - n*y`` for some integer *n* such that the result has From e271e9c0c739a4155a87fdfab0df6f4e4cc1f715 Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Tue, 12 Nov 2024 18:24:47 +0100 Subject: [PATCH 13/14] Move notes next to the related functions --- Doc/library/math.rst | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index bbbee40f3e32b7..7765472a07b99e 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -291,6 +291,11 @@ Floating point arithmetic Return the fractional and integer parts of *x*. Both results carry the sign of *x* and are floats. + Note that :func:`modf` has a different call/return pattern + than its C equivalents: it takes a single argument and return a pair of + values, rather than returning its second return value through an 'output + parameter' (there is no such thing in Python). + .. function:: remainder(x, y) @@ -328,11 +333,6 @@ Python floats typically carry no more than 53 bits of precision (the same as the platform C double type), in which case any float *x* with ``abs(x) >= 2**52`` necessarily has no fractional bits. -Note that :func:`modf` has a different call/return pattern -than its C equivalents: it takes a single argument and return a pair of -values, rather than returning its second return value through an 'output -parameter' (there is no such thing in Python). - Floating point manipulation functions ------------------------------------- @@ -351,6 +351,10 @@ Floating point manipulation functions returns ``(0.0, 0)``, otherwise ``0.5 <= abs(m) < 1``. This is used to "pick apart" the internal representation of a float in a portable way. + Note that :func:`frexp` has a different call/return pattern + than its C equivalents: it takes a single argument and return a pair of + values, rather than returning its second return value through an 'output + parameter' (there is no such thing in Python). .. function:: isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) @@ -457,12 +461,6 @@ Floating point manipulation functions .. versionadded:: 3.9 -Note that :func:`frexp` has a different call/return pattern -than its C equivalents: it takes a single argument and return a pair of -values, rather than returning its second return value through an 'output -parameter' (there is no such thing in Python). - - Power, exponential and logarithmic functions -------------------------------------------- From a45e98e753bf97718ab7ae00d3f343c6152ff2d8 Mon Sep 17 00:00:00 2001 From: Joseph Martinot-Lagarde Date: Sat, 16 Nov 2024 23:45:12 +0100 Subject: [PATCH 14/14] Implementation details back to the bottom --- Doc/library/math.rst | 49 ++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/Doc/library/math.rst b/Doc/library/math.rst index 7765472a07b99e..bf79b23a72bbf9 100644 --- a/Doc/library/math.rst +++ b/Doc/library/math.rst @@ -121,31 +121,6 @@ noted otherwise, all return values are floats. ==================================================== ============================================ -.. impl-detail:: - - The :mod:`math` module consists mostly of thin wrappers around the platform C - math library functions. Behavior in exceptional cases follows Annex F of - the C99 standard where appropriate. The current implementation will raise - :exc:`ValueError` for invalid operations like ``sqrt(-1.0)`` or ``log(0.0)`` - (where C99 Annex F recommends signaling invalid operation or divide-by-zero), - and :exc:`OverflowError` for results that overflow (for example, - ``exp(1000.0)``). A NaN will not be returned from any of the functions - above unless one or more of the input arguments was a NaN; in that case, - most functions will return a NaN, but (again following C99 Annex F) there - are some exceptions to this rule, for example ``pow(float('nan'), 0.0)`` or - ``hypot(float('nan'), float('inf'))``. - - Note that Python makes no effort to distinguish signaling NaNs from - quiet NaNs, and behavior for signaling NaNs remains unspecified. - Typical behavior is to treat all NaNs as though they were quiet. - - -.. seealso:: - - Module :mod:`cmath` - Complex number versions of many of these functions. - - Number-theoretic functions -------------------------- @@ -839,5 +814,29 @@ Constants It is now always available. +.. impl-detail:: + + The :mod:`math` module consists mostly of thin wrappers around the platform C + math library functions. Behavior in exceptional cases follows Annex F of + the C99 standard where appropriate. The current implementation will raise + :exc:`ValueError` for invalid operations like ``sqrt(-1.0)`` or ``log(0.0)`` + (where C99 Annex F recommends signaling invalid operation or divide-by-zero), + and :exc:`OverflowError` for results that overflow (for example, + ``exp(1000.0)``). A NaN will not be returned from any of the functions + above unless one or more of the input arguments was a NaN; in that case, + most functions will return a NaN, but (again following C99 Annex F) there + are some exceptions to this rule, for example ``pow(float('nan'), 0.0)`` or + ``hypot(float('nan'), float('inf'))``. + + Note that Python makes no effort to distinguish signaling NaNs from + quiet NaNs, and behavior for signaling NaNs remains unspecified. + Typical behavior is to treat all NaNs as though they were quiet. + + +.. seealso:: + + Module :mod:`cmath` + Complex number versions of many of these functions. + .. |nbsp| unicode:: 0xA0 :trim: