Atan2

Constants¶

The mathematical constant π = 3.141592…, to available precision.

The mathematical constant e = 2.718281…, to available precision.

The mathematical constant τ = 6.283185…, to available precision.
Tau is a circle constant equal to 2π, the ratio of a circle’s circumference to
its radius. To learn more about Tau, check out Vi Hart’s video Pi is (still)
Wrong, and start celebrating
Tau day by eating twice as much pie!

New in version 3.6.

A floating-point positive infinity. (For negative infinity, use
.) Equivalent to the output of .

New in version 3.5.

A floating-point “not a number” (NaN) value. Equivalent to the output of
.

New in version 3.5.

CPython implementation detail: The 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
for invalid operations like or
(where C99 Annex F recommends signaling invalid operation or divide-by-zero),
and for results that overflow (for example,
). 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 or
.

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.

See also

Module

Complex number versions of many of these functions.

8.2.7. Constants¶

math.pi

The mathematical constant π = 3.141592…, to available precision.

math.e

The mathematical constant e = 2.718281…, to available precision.

CPython implementation detail: The 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
for invalid operations like sqrt(-1.0) or log(0.0)
(where C99 Annex F recommends signaling invalid operation or divide-by-zero),
and 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.

See also

Module
Complex number versions of many of these functions.

9.2.7. Constants¶

math.pi

The mathematical constant π = 3.141592…, to available precision.

math.e

The mathematical constant e = 2.718281…, to available precision.

CPython implementation detail: The 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
for invalid operations like sqrt(-1.0) or log(0.0)
(where C99 Annex F recommends signaling invalid operation or divide-by-zero),
and 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.

See also

Module
Complex number versions of many of these functions.

8.2.3. Trigonometric functions¶

math.acos(x)

Return the arc cosine of x, in radians.

math.asin(x)

Return the arc sine of x, in radians.

math.atan(x)

Return the arc tangent of x, in radians.

math.atan2(y, x)

Return atan(y x), in radians. The result is between -pi and pi.
The vector in the plane from the origin to point (x, y) makes this angle
with the positive X axis. The point of is that the signs of both
inputs are known to it, so it can compute the correct quadrant for the angle.
For example, atan(1) and atan2(1, 1) are both pi/4, but atan2(-1,
-1)
is -3*pi/4.

math.cos(x)

Return the cosine of x radians.

math.hypot(x, y)

Return the Euclidean norm, sqrt(x*x + y*y). This is the length of the vector
from the origin to point (x, y).

math.sin(x)

Return the sine of x radians.

func Pow ¶

func Pow(x, y ) 

Pow returns x**y, the base-x exponential of y.

Special cases are (in order):

Pow(x, ±0) = 1 for any x
Pow(1, y) = 1 for any y
Pow(x, 1) = x for any x
Pow(NaN, y) = NaN
Pow(x, NaN) = NaN
Pow(±0, y) = ±Inf for y an odd integer < 0
Pow(±0, -Inf) = +Inf
Pow(±0, +Inf) = +0
Pow(±0, y) = +Inf for finite y < 0 and not an odd integer
Pow(±0, y) = ±0 for y an odd integer > 0
Pow(±0, y) = +0 for finite y > 0 and not an odd integer
Pow(-1, ±Inf) = 1
Pow(x, +Inf) = +Inf for |x| > 1
Pow(x, -Inf) = +0 for |x| > 1
Pow(x, +Inf) = +0 for |x| < 1
Pow(x, -Inf) = +Inf for |x| < 1
Pow(+Inf, y) = +Inf for y > 0
Pow(+Inf, y) = +0 for y < 0
Pow(-Inf, y) = Pow(-0, -y)
Pow(x, y) = NaN for finite x < 0 and finite non-integer y

▹ Example

▾ Example

package main

import (
«fmt»
«math»
)

func main() {
c := math.Pow(2, 3)
fmt.Printf(«%.1f», c)
}

8.0

Run
Format

Степени, логарифмирование, экспоненцирование

math.pow(x, y)
Возвращает x в степени y.

В ситуациях или данная функция всегда возвращает \(1\) даже если x равен NaN, Inf или -Inf. Однако, если x и y являются конечными числами, причем x отрицательное, а y не целое, то будет вызвано исключение ValueError:

math.sqrt(x)
Возвращает квадратный корень числа x.
math.log(x)
Если указано только число x, то возвращается натуральный логарифм данного числа. Если указано число x и основание base, то возвращается логарифм числа по указанному основанию.

По сути, команда равносильна команде :

math.log10(x)
Возвращает десятичный логарифм числа x, вычисление которого происходит немного точнее, чем .
math.log2(x)
Возвращает двоичный логарифм числа x, вычисление которого происходит немного точнее, чем .
math.log1p(x)
Возвращает натуральный логарифм от x увеличенного на \(1\) (), значение которого расчитывается более точно, особенно для небольших чисел x.
math.exp(x)
Возвращает .
math.expm1(x)
Возвращает , которое вычисляется значительно точнее, чем , особенно для небольших чисел x.

Java Integer Math

Математические операции, выполняемые с целочисленными типами Java (byte, short, int и long), ведут себя немного иначе, чем обычные математические операции. Поскольку целочисленные типы не могут содержать дроби, в каждом вычислении с одним или несколькими целочисленными типами все дроби в результате обрезаются. Посмотрите на это математическое выражение:

int result = 100 / 8;

Результат этого деления будет 12,5, но так как два числа являются целыми числами, фракция .5 обрезается. Результат, следовательно, всего 12.

Округление также происходит в подрезультатах больших вычислений.

С плавающей точкой Math

Java содержит два типа данных с плавающей точкой: float и double. Они могут содержать дроби в числах. Если нужны дробные выражения в математических выражениях, вы должны использовать один из этих типов данных. Вот пример математического выражения с плавающей точкой:

double result = 100 / 8;

Несмотря на то, что переменная результата теперь имеет тип с плавающей запятой (double), конечный результат по-прежнему равен 12 вместо 12,5. Причина в том, что оба значения в математическом выражении (100 и 8) оба являются целыми числами. Таким образом, результат деления одного на другое сначала преобразуется в целое число (12), а затем присваивается переменной результата.

Чтобы избежать округления вычислений, необходимо убедиться, что все типы данных, включенные в математическое выражение, являются типами с плавающей запятой. Например, вы могли бы сначала присвоить значения переменным с плавающей запятой следующим образом:

double no1 = 100;
double no2 = 8;

double result = no1 / no2;

Теперь переменная результата будет иметь значение 12,5.

В Java есть способ заставить все числа в расчете быть переменными с плавающей точкой. Вы ставите числа с большой буквы F или D. Вот пример:

double result = 100D / 8D;

Обратите внимание на прописные буквы D после каждого числа. Этот верхний регистр D говорит Java, что эти числа должны интерпретироваться как числа с плавающей запятой, и, таким образом, деление должно быть делением с плавающей запятой, которое сохраняет дроби вместо их обрезания

На самом деле вы также можете сделать число длинным, добавив суффикс числа к верхнему регистру L, но long по-прежнему является целочисленным типом, поэтому он не будет сохранять дробные части в вычислениях.

Точность с плавающей точкой

Типы данных с плавающей точкой не являются точными на 100%. Вы можете столкнуться с ситуациями, когда числа со многими дробями не складываются с ожидаемым числом. Если вычисление с плавающей запятой приводит к числу с большим количеством дробей, чем может обработать число с плавающей запятой или двойное число, дроби могут быть обрезаны. Конечно, заданная точность может быть более чем достаточной для многих типов вычислений, но имейте в виду, что дроби могут фактически быть отсечены.

Посмотрите:

double resultDbl3 = 0D;
System.out.println("resultDbl3 = " + resultDbl3);

for(int i=0; i<100; i++){
    resultDbl3 += 0.01D;
}
System.out.println("resultDbl3 = " + resultDbl3);

Вывод выводится при выполнении этого кода с Java 8:

resultDbl3 = 0.0
resultDbl3 = 1.0000000000000007

Первый оператор System.out.println() правильно печатает значение 0.0, которое является начальным значением переменной resultDbl3.

Однако второй оператор System.out.println() выводит несколько странный результат. Добавление значения 0,01 к 0 всего 100 раз должно привести к значению 1,0, верно? Но каким-то образом окончательный результат 1.0000000000000007. Как видите, что-то не так во фракциях.

Обычно неточность с плавающей запятой незначительна, но все же важно знать об этом

8.2.2. Power and logarithmic functions¶

math.exp(x)

Return e**x.

math.expm1(x)

Return e**x - 1. For small floats x, the subtraction in exp(x) - 1
can result in a significant loss of precision; the
function provides a way to compute this quantity to full precision:

>>> from math import exp, expm1
>>> exp(1e-5) - 1  # gives result accurate to 11 places
1.0000050000069649e-05
>>> expm1(1e-5)    # result accurate to full precision
1.0000050000166668e-05

New in version 3.2.

math.log(x, base)

With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base,
calculated as log(x)/log(base).

math.log1p(x)

Return the natural logarithm of 1+x (base e). The
result is calculated in a way which is accurate for x near zero.

math.log10(x)

Return the base-10 logarithm of x. This is usually more accurate
than log(x, 10).

math.pow(x, y)

Return x raised to the power y. Exceptional cases follow
Annex ‘F’ of the C99 standard as far as possible. In particular,
pow(1.0, x) and pow(x, 0.0) always return 1.0, even
when x is a zero or a NaN. If both x and y are finite,
x is negative, and y is not an integer then pow(x, y)
is undefined, and raises .

Unlike the built-in ** operator, converts both
its arguments to type . Use ** or the built-in
function for computing exact integer powers.

Constants

Mathematical constants.

const (
    E   = 2.71828182845904523536028747135266249775724709369995957496696763 
    Pi  = 3.14159265358979323846264338327950288419716939937510582097494459 
    Phi = 1.61803398874989484820458683436563811772030917980576286213544862 

    Sqrt2   = 1.41421356237309504880168872420969807856967187537694807317667974 
    SqrtE   = 1.64872127070012814684865078781416357165377610071014801157507931 
    SqrtPi  = 1.77245385090551602729816748334114518279754945612238712821380779 
    SqrtPhi = 1.27201964951406896425242246173749149171560804184009624861664038 

    Ln2    = 0.693147180559945309417232121458176568075500134360255254120680009 
    Log2E  = 1 / 
    Ln10   = 2.30258509299404568401799145468436420760110148862877297603332790 
    Log10E = 1 / 
)

Floating-point limit values.
Max is the largest finite value representable by the type.
SmallestNonzero is the smallest positive, non-zero value representable by the type.

const (
    MaxFloat32             = 3.40282346638528859811704183484516925440e+38  
    SmallestNonzeroFloat32 = 1.401298464324817070923729583289916131280e-45 

    MaxFloat64             = 1.797693134862315708145274237317043567981e+308 
    SmallestNonzeroFloat64 = 4.940656458412465441765687928682213723651e-324 
)

Integer limit values.

const (
    MaxInt8   = 1<<7 - 1
    MinInt8   = -1 << 7
    MaxInt16  = 1<<15 - 1
    MinInt16  = -1 << 15
    MaxInt32  = 1<<31 - 1
    MinInt32  = -1 << 31
    MaxInt64  = 1<<63 - 1
    MinInt64  = -1 << 63
    MaxUint8  = 1<<8 - 1
    MaxUint16 = 1<<16 - 1
    MaxUint32 = 1<<32 - 1
    MaxUint64 = 1<<64 - 1
)

9.2.1. Number-theoretic and representation functions¶

math.ceil(x)

Return the ceiling of x, the smallest integer greater than or equal to x.
If x is not a float, delegates to x.__ceil__(), which should return an
value.

math.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.

math.fabs(x)

Return the absolute value of x.

math.factorial(x)

Return x factorial. Raises if x is not integral or
is negative.

math.floor(x)

Return the floor of x, the largest integer less than or equal to x.
If x is not a float, delegates to x.__floor__(), which should return an
value.

math.fmod(x, y)

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
the same sign as x and magnitude less than abs(y). Python’s x % y
returns a result with the sign of y instead, and may not be exactly computable
for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but
the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be
represented exactly as a float, and rounds to the surprising 1e100. For
this reason, function is generally preferred when working with
floats, while Python’s x % y is preferred when working with integers.

math.frexp(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.

math.fsum(iterable)

Return an accurate floating point sum of values in the iterable. Avoids
loss of precision by tracking multiple intermediate partial sums:

>>> sum()
0.9999999999999999
>>> fsum()
1.0

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.

math.isfinite(x)

Return True if x is neither an infinity nor a NaN, and
False otherwise. (Note that 0.0 is considered finite.)

New in version 3.2.

math.isinf(x)

Return True if x is a positive or negative infinity, and
False otherwise.

math.isnan(x)

Return True if x is a NaN (not a number), and False otherwise.

math.ldexp(x, i)

Return x * (2**i). This is essentially the inverse of function
.

math.modf(x)

Return the fractional and integer parts of x. Both results carry the sign
of x and are floats.

math.trunc(x)

Return the value x truncated to an
(usually an integer). Delegates to
x.__trunc__().

Note that and 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
parameter’ (there is no such thing in Python).

func Atan2 ¶

func Atan2(y, x ) 

Atan2 returns the arc tangent of y/x, using
the signs of the two to determine the quadrant
of the return value.

Special cases are (in order):

Atan2(y, NaN) = NaN
Atan2(NaN, x) = NaN
Atan2(+0, x>=0) = +0
Atan2(-0, x>=0) = -0
Atan2(+0, x<=-0) = +Pi
Atan2(-0, x<=-0) = -Pi
Atan2(y>0, 0) = +Pi/2
Atan2(y<0, 0) = -Pi/2
Atan2(+Inf, +Inf) = +Pi/4
Atan2(-Inf, +Inf) = -Pi/4
Atan2(+Inf, -Inf) = 3Pi/4
Atan2(-Inf, -Inf) = -3Pi/4
Atan2(y, +Inf) = 0
Atan2(y>0, -Inf) = +Pi
Atan2(y<0, -Inf) = -Pi
Atan2(+Inf, x) = +Pi/2
Atan2(-Inf, x) = -Pi/2

▹ Example

▾ Example

package main

import (
«fmt»
«math»
)

func main() {
fmt.Printf(«%.2f», math.Atan2(0, 0))
}

0.00

Run
Format

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector